usestate callback with code examples

In React, the useState hook is one of the most frequently used hooks. It allows developers to declare a state variable and update it anytime the component re-renders with new data. useState is what makes React a powerful tool for building dynamic user interfaces. However, sometimes you may need to perform some additional actions after the state has been updated. This is where the useState callback comes in handy.

In this article, we will discuss what the useState callback is and why you may need it, and provide several examples of how to use it.

What is the useState callback?

A useState callback is simply a function that is called after the state has been updated. It is passed as the second argument to the useState hook. The callback is executed immediately after the React component has updated its state. This makes it possible to perform some additional actions after the state has been updated.

Why you may need a useState callback

There are several reasons why you may need a useState callback:

  1. When you want to perform an action after the state has been updated.

For instance, if you want to log the new state value after each state update, you can pass a callback function to the setState method. This will ensure that the log is only called after the state has been updated.

  1. When you want to perform an action before the state is updated.

Sometimes, you may want to perform an action before the state is updated. For instance, you may want to save the current state to local storage before updating it. You can achieve this by using a callback that updates the local storage.

  1. When you want to synchronize the state with other components.

In some scenarios, you may have multiple components that rely on the same state. For instance, you may have two components that both update the same state variable. To ensure that both components are always in sync, you can use a useState callback to update the state in both components.

How to use useState callback – examples

Example 1: Updating local storage after state update

In this example, we will use a callback to update the local storage after the state has been updated.

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

useEffect(() => {
    localStorage.setItem('count', count);
}, [count]);

const handleIncrement = () => {
    setCount(prevCount => prevCount + 1, () => {
        localStorage.setItem('count', count + 1);

In this example, we are using the useState hook to manage a count state variable. After the component updates the count state, the useEffect hooks saves the data in the local storage. Additionally, we are using the handleIncrement function to increment the count and update the local storage immediately after the state has been updated.

Example 2: Synchronizing state between multiple components

In this example, we will use a callback to keep two components in sync.

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

const handleIncrement = () => {
    setCount(prevCount => prevCount + 1, () => {
        props.onCountChange(count + 1);

return (
        <IncrementButton onClick={handleIncrement} />

In this example, we have two components that rely on the same count state. The handleIncrement function is used to increment the count and then update the props onCountChange. The onCountChange function is a callback function that is implemented in another component. This callback function is used to ensure that the other component is updated with the new count value.


The useState callback is a powerful tool that makes it possible to perform additional actions after the state has been updated. It can be used to synchronize state between multiple components, update local storage, and perform other actions before or after the state is updated. By using it, developers can improve the functionality and performance of their React applications.

here's some additional information on previous topics that may be helpful:

React Hooks

React Hooks are a set of functions that were introduced in React 16.8. They allow you to use state and other React features without writing a class component. Previously, the only way to manage state in a React component was through class components using the setState method. Now, with Hooks, functional components can use state and other features similar to class components.

React Hooks provide an efficient and easier way to manage state and other functionality within a React component. There are several Hooks available, including useState, useEffect, useContext, useReducer, useMemo, and useCallback. Each Hook serves a specific purpose, for example, useState allows you to add state to a component, useEffect lets you perform side effects in a component, and useContext lets you share data between multiple components.

React Flux Architecture

React Flux Architecture is a pattern that is often used to manage state in React applications. It is a model that emphasizes the uni-directional flow of data, which means that data flows in one direction: down the component hierarchy. This is in contrast to two-way data binding, which can lead to bugs and performance issues.

Flux consists of several components: Actions, Dispatcher, Stores, and Views. Actions are objects that describe a change that will be made to the state, while the Dispatcher is a central hub that receives the Actions and dispatches them to the appropriate Store. Stores are responsible for managing the application's state, and Views are React components that render the state from the Stores.

Flux Architecture provides a clear separation between concerns, making the code easier to understand and maintain. It is also scalable, meaning that it can be used for large-scale applications. One popular implementation of Flux is Redux, which provides a predictable, scalable, and easy-to-use architecture for managing state in React applications.

React Router

React Router is a library that allows you to navigate between different pages within a React application. It is a popular tool for building single-page applications (SPAs), which are web apps that load a single HTML page and dynamically update the content of the page as the user interacts with the app.

React Router provides several components that allow you to define routes within your application, including Route, Switch, BrowserRouter, Link, and Redirect. By using these components, you can define the different pages within your app and how they are accessed by the user.

React Router makes it easy to add dynamic routing capabilities to your React app. It supports a variety of features, such as nested routes, URL parameters, and code splitting. Additionally, it is highly customizable, allowing you to create a unique user experience for your app.

Overall, each of these topics plays an important role in building robust, dynamic, and scalable React applications. By understanding and utilizing these concepts, developers can build more efficient and intuitive apps that meet the needs of their users.

Popular questions

Here are five common questions about useState callback with answers:

  1. What is the purpose of a useState callback?

The purpose of a useState callback is to perform additional actions after the state has been updated in a React component. It allows you to execute code immediately after a state update has occurred.

  1. How is a useState callback implemented?

A useState callback is implemented by passing a callback function as the second argument to the useState hook. This function will be executed immediately after the state has been updated.

  1. Can multiple callbacks be used with useState?

No, only one callback can be used with useState as it is the second argument that accepts a single function.

  1. Can you have a useState callback without a set state function?

No, useState callback is used primarily with setState function that is returned by the useState hook.

  1. What are some possible use cases for a useState callback?

There are several use cases for a useState callback, such as updating local storage after a state update, synchronizing state between multiple components, and performing actions before or after the state is updated. For example, you can use a callback function after state update to fetch data from an API. Or you can update the URL after the state has changed using a callback function.



My passion for coding started with my very first program in Java. The feeling of manipulating code to produce a desired output ignited a deep love for using software to solve practical problems. For me, software engineering is like solving a puzzle, and I am fully engaged in the process. As a Senior Software Engineer at PayPal, I am dedicated to soaking up as much knowledge and experience as possible in order to perfect my craft. I am constantly seeking to improve my skills and to stay up-to-date with the latest trends and technologies in the field. I have experience working with a diverse range of programming languages, including Ruby on Rails, Java, Python, Spark, Scala, Javascript, and Typescript. Despite my broad experience, I know there is always more to learn, more problems to solve, and more to build. I am eagerly looking forward to the next challenge and am committed to using my skills to create impactful solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top