React Function Component - (Side) Effect (useEffect Hook)

About

Effect Hook 1) is a hook that lets you perform side effects in functional components, and is similar to lifecycle methods in classes.

An effect is also known as a side-effect

Example of effect:

  • Setting up a subscription,
  • Manually changing the DOM in React components

The function that is passed is also called an effect

By default, an effect is executed after every render (regardless of whether the component just mounted, or if it has been updated)

Example

Counter

Updating at the same time, the page and the document.title

React Hook Side Effect Doc Title

  • The component
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);
  
  // Similar to componentDidMount and componentDidUpdate:
  React.useEffect(() => {
    // Update the document title using the browser API
    let doc = window.document
    if (inIframe){
      doc = window.parent.document;
    } 
    doc.title = `You clicked ${count} times`;
  });
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • Just to detect an iframe to be able to get the top document in embedded code
function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}
  • The rendering part
ReactDOM.render(
    <Example/>,
    document.getElementById('root')
);
  • The root element where React will render
<div id="root"></div>

Lifecycle

See React Function Component - Lifecycle

Syntax

Effects are scheduled with:

  • useEffect
  • or useLayoutEffect

useEffect

See What is React useEffect?

useLayoutEffect

synchronous

Effect vs Class LifeCycle Method

  • Asynchronous UI update - Unlike componentDidMount or componentDidUpdate, useEffect effects don’t block the browser from updating the screen. In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect.
  • Resource release: A release of the resource happens in a the componentWillUnmount method whereas in a function, it happens with the cleanup function
  • No update code: There is no special place for handling updates (componentDidUpdate) because the useEffect code is run on mount and update.

Management

Skip

Skipping effect

Cleanup

The function returned by an effect is called the cleanup function.

This function is executed when the component Unmount and Update. See lifecycle demo

You can still skip the cleanup for update for perf reason. See skip

Run once

When you want to run the function only once, pass an empty array. Because the value will never change, the function will never run again.

Example with a google analytics on a page level that log a page view.

React.useEffect(() => {
    initGA();
    logPageView();
    Router.events.on('routeChangeComplete', logPageView);
  }, []);





Discover More
React - Component (User-defined Element)

A component is a user-defined react element in the React tree. Components let you split the UI into independent, reusable pieces, and think each piece in isolation. Conceptually, components are like...
React - Fetch

in react that fetch data from an API endpoint Class Component: see Function Component: see
React Class Component - Rendering (Mounting/Unmounting)

for a class component In a class component, mounting and unmounting are methods: componentDidMount: Runs after the component output has been rendered to the DOM componentWillUnmount componentDidUpdate...
React Function Component - Lifecycle

lifecycle rendering in functional component are managed through effect A mount run the body of the effect function (equivalent to a mount) A unmount (called also cleanup) runs the function returned...
What are React Hooks?

hooks are functions that: let you hook into React state and lifecycle features from function components. can be used only in a functional component (ie not inside classes component) may call other...
What is React useEffect?

useEffectuseEffect is an effect that: is asynchronous and executes at the end of the rendering. Specifically, it runs at the end of a commit after the screen updates, after every render When...



Share this page:
Follow us:
Task Runner