DEV Community

Coder
Coder

Posted on

React useState with Callback

React useState with Callback

As a React developer, you may have encountered a scenario where you need to update the state of your component based on the previous state. Using useState alone may not accomplish this requirement. That's where the useCallback hook comes into play. In this post, we'll explore using useState with a useCallback function to update state correctly.

Understanding useState and Callback

To understand useState and callback, let's start by exploring the useState hook. In React, the useState hook enables us to add state to functional components. The useState hook takes an initial value as its argument and returns a tuple of state and a function to update that state value.

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

In the example above, 0 is the initial state value that we pass to the useState function. The useState function returns two values, the count state value, and the setCount function to update that state value.

However, there exists an issue with this approach - the setCount function always overwrites the existing value every time it's called, thereby resetting the state to its initial value.

For a case where you need to update the state based on the previous value, the useCallback hook comes in handy. Using useCallBack enables our component to create a memoized version of the function passed to it, which then allows React to optimize and prevent the function from being re-executed on each re-render.

Updating State using useCallback

To update state using useCallback, we start by implementing useState in our component as usual:

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
}
Enter fullscreen mode Exit fullscreen mode

After our useState hook, we then add useCallback, which takes a function as an argument and returns a memorized version of the function for re-use:

import React, { useState, useCallback } from "react";

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

  const incrementCount = useCallback(() => {
    setCount(count + 1);
  }, [count]);
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we've added a useCallback hook that uses the setCount function. Each time setCount is called, it increases the count state value by one. Notice that we've also passed count as the dependency parameter in the useCallback hook.

This dependency array ensures that incrementCount is only updated when count changes. Any change to the state value triggers the re-execution of incrementCount, and since we're using useCallback, the memoized version of the function is used instead, which improves performance.

Examples with Code

Here's a simple example demonstrating the use of useCallback with useState.

import React, { useState, useCallback } from "react";

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

  const incrementCount = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Above, we have a simple counter that displays its value and a button for incrementing the count value. The incrementCount function is used to handle the click event on the button.

With each successive click on the increment button, incrementCount is called and sets the count state value to the current value of count plus one. The setCount function is accessed via the useCallback hook.

Notice that we've passed count as a dependency to the useCallback hook. It ensures that the function stored in incrementCount is only re-created when count changes, which improves performance.

Conclusion

In conclusion, useState and Callback are useful hooks in React, especially in cases where we need to update a state based on its previous value. The useCallback hook memoizes its input function, thereby preventing unnecessary re-renders, whereas useState adds state to the functional component, thereby allowing us to update the component's state.

Using useState with useCallback makes our code more efficient and readable. We must always try to optimize our components to avoid unnecessary re-renders and improve performance.

Overall, useState with useCallback is a powerful combination to update state values correctly in React.

Top comments (0)