useEffect Hook

useEffect hook allows you to perform side effects like fetching data from server, timers or updating DOM in your functional component.

useEffect accepts two arguments:

  1. Closure (Required)
  2. Array of Dependency (Optional)

There are few use cases of the second optional argument that resembles some of the lifecycle of the class component.

Omitting the second argument

useEffect(() => {
  // Omit the second argument will always re-run the useEffect for every rendering
});

Empty array of second argument

useEffect(() => {
  // Runs only when mount
  // Similar to componentDidMount
}, []);

Some values in the array

useEffect(() => {
  // Runs when mount and when any value in the array is changed
  // Similar to componentDidUpdate
}, [valueA, valueB]);

Effect Cleanup

We may need to clean up the effect sometimes to prevent memory leaks. Timeouts, subscriptions, event listeners are some of the effects that may need to clean up when the dependencies have changed the component is unmounted. It is similar to componentWillUnmount in the class component.

To clean up an effect, you need to return a function at the end of the effect which the function will be called when the component re-renders or unmount.

useEffect(() => {
  const timer = setTimeout(() => {
    // Do something
  }, 1000);

  return () => {
    // This method will be called when the effect is cleaning up
    clearTimeout(timer);
  }
}, []);
Exit mobile version
%%footer%%