Skip to main content

Command Palette

Search for a command to run...

useEffect in React

Updated
3 min read
useEffect in React

The useEffect() hook is part of functional programming and the word ‘effect’ is used to describe the “side effect” of a REACT app.

Common side effects include:

  • API requests.

  • Using unpredictable timing functions. e.g setTimeOut or setInterval.

  • Directly updating the DOM. e.g using Document/ Window.

Structure

The useEffect() hook accepts two arguments. The dependency normally refers to the re-render array. This array includes all the dependencies that the side effect relies on.

useEffect(<function>, <dependency>

Use Case 1 (Run on first render)

Suppose that we want to fetch data from an API. This usually happens when the app is initially loaded. So to make sure that the API is called only on the first render we write:

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

Example

  const [todos, setTodos] = useState([]);
  useEffect(() => {fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json =>  setTodos(json))

  },[])

Use case 2: Re-render On Dependency Value Change

We have seen from the example above that when we want the effect to run on the first render we include an empty array. But in some instances, we may want the effect to re-render based on certain dynamic values. This is when we include dynamic values inside the dependency array.

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

Example

export default function App() {
  const [number, setNumber] = useState(0);
  const [render, setRender] = useState(0)
  useEffect(()=>{
    setRender(number +1)
  },[number])

  const addTwo = () => {
    setNumber(number+1);
  };

  return (
    <div className="App">
      <button onClick={addTwo}>+</button>
      <h3>{number}</h3>
      <h4>number of renders {render} </h4>
    </div>
  );
}

The example above shows how re-rendering is done using the dynamic value ‘number’. Every time the ‘number’ changes the re-render value ‘render’ changes since the side effect re-renders based on the ‘number’ value.

Effect Clean up

The side effects are not supposed to run forever. At some point, the effect must be shut off in order to reduce memory use. All that is needed is a return function that clears a pre-defined time-out.

export default function App() {
  const [number, setNumber] = useState(0);
  const [render, setRender] = useState(0)
  useEffect(()=>{
    let timer = setTimeout(setRender(number +1),1000)
    return ()=>{
      return  setTimeout(timer)
    }

  },[number])

  const addTwo = () => {
    setNumber(number+1);
  };
  return (
    <div className="App">
      <button onClick={addTwo}>+</button>
      <h3>{number}</h3>
      <h4>number of renders {render} </h4>
    </div>
  );
}

The cleanup function will be called when the component is unmounted. The cleanup function is not required in every instance and it is only used when there is a need to stop a repeated side effect when the component unmounts.

Make sure to follow my blog for more REACT tutorials.

Happy coding!