React Hook: useEffect

Basically you can think of useEffect Hook as componentDidMountcomponentDidUpdate, and componentWillUnmount combined

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.

useEffect() is for side-effects

A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don’t target the output value, then these calculations are named side-effects.

Examples of side-effects are fetch requests, manipulating DOM directly, using timer functions like setTimeout(), and more

The component rendering and side-effect logic are independent. It would be a mistake to perform side-effects directly in the body of the component, which is primarily used to compute the output.

Source:

https://reactjs.org/docs/hooks-effect.html

https://dmitripavlutin.com/react-useeffect-explanation/#1-useeffect-is-for-side-effects

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.