DEV Community

Cover image for When do you use setState with a callback?
Clara Situma
Clara Situma

Posted on

When do you use setState with a callback?

You would use a callback with the useState hook in a situation where the state update depends on the previous value of the state.

This is because the useState hook only provides a way to update the state with a new value, but it does not give you access to the previous value of the state. In order to access the previous value of the state, you would need to use a callback function with the useState hook.

Here is an example of how you might use a callback with the useState hook:

const [count, setCount] = useState(0);

// update the count by adding 1 to the previous value

setCount(prevCount => prevCount + 1);

Enter fullscreen mode Exit fullscreen mode

In this example, the useState hook is being used to manage a piece of state called count.

The initial value of count is set to 0 using the useState hook. Then, the setCount function is called with a callback that adds 1 to the previous value of count. This ensures that the new value of count is always one greater than the previous value.
It is important to note that you do not always have to use a callback with the useState hook.

You only need to use a callback if the state update depends on the previous value of the state. In situations where the state update does not depend on the previous value, you can simply pass the new value directly to the setCount function.

Here is an example of updating the state without using a callback:

const [count, setCount] = useState(0);

// update the count by setting it to a specific value
setCount(10);
Enter fullscreen mode Exit fullscreen mode

In this example, the setCount function is called with a new value of 10, and the state is updated accordingly. Because the update does not depend on the previous value of the state, a callback is not needed.

REAL EXAMPLE:

Here is an example where a React component uses the useState and useEffect hooks to manage state and perform side effects.

The useState hook is used to create a piece of state called index, which is initially set to 0. The useEffect hook is used to set up an interval that will update the index state every 3 seconds.

import { useState, useEffect } from "react";
import pictures from "./data/pictures";

import React from "react";

function Gallery() {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setIndex((currentValue) => {
        return (currentValue + 1) % pictures.length;
      });
    }, 3000);

    return () => clearInterval(interval);
  }, []);


  return (
    <div className="Gallery">
      <img src={pictures[index].image} alt="gallery_photos" />
    </div>
  );
}

export default Gallery;

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ramazanima profile image
Ali Ramazani

Great article.