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

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Function Component

1 - About

Effect Hook 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)

Advertising

3 - Example

3.1 - Counter

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

  • The component
example.js
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
example.js
ReactDOM.render(
    <Example/>,
    document.getElementById('root')
);
  • The root element where React will render
index.html
<div id="root"></div>

3.2 - Lifecycle

4 - Syntax

Effects are scheduled with:

  • useEffect
  • or useLayoutEffect
Advertising

4.1 - useEffect

asynchronous

4.2 - useLayoutEffect

synchronous

5 - 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.

6 - Management

6.1 - Skip

6.2 - 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

Advertising
web/javascript/react/function/effect.txt · Last modified: 2019/06/17 15:47 by gerardnico