Twitter LogoFacebook Logo
useEffect Hook
Learn what is the useEffect hook in React and how to use it.
By: King

In React, useEffect is a built-in hook that allows you to perform side effects in components. Side effects refer to any code that needs to be executed outside the regular flow of the component, such as fetching data, subscribing to events, or manipulating the DOM.


Let's see how this works:

The useEffect Hook

Step 1:


Import useEffect from React.

import { useEffect } from 'react';

Step 2:

Call useEffect:

useEffect( () => {}, [] );

It accepts two arguments:

1. Callback
2. Dependency Array

The callback function passed to useEffect will be executed after the component has rendered. It can contain any code.

function App() {
  useEffect(() => {

    console.log("UseEffect activated");

  }, []);

  return (<div>My App</div>);
}

The second argument, the dependencies array, is an optional parameter that allows you to control when the effect is re-executed. 


It specifies the values that the effect depends on. If any of the values in the dependencies array change, the effect will be re-executed. If the dependencies array is empty, the effect will only run once when the component mounts.

function App() {
  let [ name, setName ] = useState("");
  let [ age, setAge ] = useState(0);

  useEffect(() => {

    console.log("UseEffect activated");

  }, [name, age]);

  return (<div>My App</div>);
}

In the example, when either name or age changes, the code in the useEffect callbkack will be executed.

Cleanup Function

Additionally, the callback function can optionally return a cleanup function. This cleanup function will be executed when the component is unmounted or when the dependencies change and the effect needs to be re-executed

It can be used to cancel requests, remove event listeners, or perform any necessary cleanup to avoid memory leaks.

useEffect( () => {
    return () => {

        // This will not execute unless the component is destroyed
        // or when the useEffect reactivates
        console.log("Cleanup section activated");

    }
}, [] );


Sign In