DEV Community

Cover image for React useEffect Hooks
Keerthana M
Keerthana M

Posted on

React useEffect Hooks

React useEffect Hooks

The useEffect Hook allows you to perform side effects in your components.

syntax:

import { useEffect } from 'react';
useEffect(() => {
  // 1. Your side-effect logic goes here

  return () => {
    // 2. Optional cleanup function goes here
  };
}, [dependencies]); // 3. Optional dependency array
Enter fullscreen mode Exit fullscreen mode

side effects are:

  1. Fetching data,
  2. Directly updating the DOM,
  3. Timers.
  • Data Fetching: Fetch data from an API when the component mounts or when a specific state value changes.
  • Event Listeners: Add or remove event listeners, such as scroll or resize, when the component is mounted or unmounted.
  • Timers and Intervals:Manage time-based operations like setting up intervals, timeouts, or animations.
  • Updating Document Title: Change the document title when a component is mounted or unmounted.

  • UseEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect.
  • This is not what we want. There are several ways to control when side effects run.

  • It include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array.

1. No dependency passed:

useEffect(() => {
  //Runs on every render
});
Enter fullscreen mode Exit fullscreen mode

2. An empty array:

useEffect(() => {
  //Runs only on the first render
}, []);
Enter fullscreen mode Exit fullscreen mode

3.Dependencies

  • The useEffect hook accepts two arguments: a function and an optional array of dependencies.

  • The function contains the side effect logic, and the array specifies when the effect should re-run.

useEffect(() => {
// Effect logic here
}, [dependency1, dependency2]);
Enter fullscreen mode Exit fullscreen mode

4. Props or state values:

useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [prop, state]);
Enter fullscreen mode Exit fullscreen mode

Effect Cleanup

  • Some effects require cleanup to reduce memory leaks.
  • Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
  • We do this by including a return function at the end of the useEffect Hook.
useEffect(() => {
const timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);

return () => clearTimeout(timer);
}, []);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)