Skip to main content

useEffect()

perform Side Effect in React.

  • useEffect() is a Hook in React that lets you perform side effects in functional components.
  • It take callback function and dependency array. If the dependency array is empty then they run after render the component at the only 1 time.

Usage Patterns

It is called within a functional component to manage tasks such as;

  • Data fetching, Subscriptions, and manually changing the DOM.
  • Cleanup logic for unmounting or before the effect runs again.

Dependency Array

  • Determines when the effect runs.
  • Empty array [] means the effect runs only once (on mount).
  • List of dependencies [dep1, dep2] means the effect runs whenever any dependency changes.

Syntax

  • The first argument is a function containing the side effect logic.
  • The second argument is an optional array of dependencies that determine when the effect should run.
useEffect(() => {}, []);
  • If you want that they re-run the useEffect after the state value is change or a variable value change then we pass those variable in the dependency array.

Syntax

const [sum, setSum] = useState(0);

useEffect(() => {}, [sum]);
  • you can clean up in the useEffect using return in the callback function.
const [sum, setSum] = useState(0);

useEffect(() => {
return () => cleanupEvents();
}, [sum]);

How it Works?

  • Mounting: When the component is first rendered, the effect runs. (run after component render)
  • Updating: If any values in the dependency array change, the effect runs again.
  • Unmounting: If a cleanup function is returned from the effect, it runs when the component is unmounted or before the effect runs again on updates.

Similarities with Class-based Components

componentDidMount, componentDidUpdate, and componentWillUnmount

  • componentDidMountuseEffect(() => { /* effect */ }, [])
  • componentDidUpdateuseEffect(() => { /* effect */ }, [dependencies])
  • componentWillUnmountuseEffect(() => { return () => { /* cleanup */ }; }, [])