State Management in React – Hooks, Context API and Redux
Last Updated : 10 May, 2025
State management is a critical concept when working with React. React components can hold local state, but as applications grow, managing state across multiple components can become complex. To help manage this complexity, React provides several tools: Hooks, Context API, and Redux.
Here are some features of State Management:
- Local State (useState): Manage data within a single component.
- Global State (Context API): Share state across multiple components.
- Centralised State (Redux): Manage complex state with a global store for large apps.
- Immutability: State cannot be directly mutated; it must be updated via functions.
- Re-renders: React re-renders components when state changes.
State Management with Hooks
React Hooks were introduced in version 16.8 and provide a way to manage state and lifecycle methods in functional components. Before hooks, class components were used for managing state, but now, functional components with hooks have become the standard for most React apps.
1. useState Hook
The
useState Hook
is
the most commonly used hook for local state management in functional components. It allows a component to have its state that can be modified using a setter function.
Syntax
const [state, setState] = useState(<default value>);
In the above syntax
- useState(<default value>): A React hook to manage state in functional components.
- <default value>: Initial value of the state (e.g., a number, string).
- [state, setState]: State holds the current value of the state, and setState is a function to update the state.
Now let's understand this with the help of an example
JavaScript import React, { useState } from 'react'; function NameInput() { const [name, setName] = useState(''); const handleInputChange = (event) => { setName(event.target.value); }; return ( <div> <h1>Enter Your Name</h1> <input type="text" value={name} onChange={handleInputChange} placeholder="Type your name" /> <p>Hello, {name ? name : 'Stranger'}!</p> </div> ); } export default NameInput;
State Management in React In this example
- useState('') initializes the name state as an empty string.
- handleInputChange updates the name state whenever the user types in the input field.
- The input field uses value={name} to display the current name, and onChange={handleInputChange} to update the state.
- The component displays a greeting: "Hello, {name}", defaulting to "Stranger" if no name is typed.
2. useReducer
useReducer hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components need to be optimized.
Syntax:
const [state, dispatch] = useReducer(reducer, initialArgs, init);
- useReducer: Manages complex state logic.
- reducer: A function that updates state based on actions.
- initialArgs: Initial state value.
- init (optional): Function to lazily initialize state.
- state: Current state.
- dispatch: Function to send actions to update the state
State Mangement with Context API
The Context API is a feature built into React that allows for global state management. It is useful when we need to share state across many components without having to pass props down through multiple levels of the component tree.
Syntax
const authContext = useContext(initialValue);
Now let's understand this with the help of example:
JavaScript //auth-context.js import React from "react"; const authContext = React.createContext({ status: null, login: () => {} }); export default authContext;
JavaScript //App.js import React, { useState } from "react"; import Auth from "./Auth"; import AuthContext from "./auth-context"; const App = () => { const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return ( <React.Fragment> <AuthContext.Provider value={{ status: authstatus, login: login }}> <Auth /> </AuthContext.Provider> </React.Fragment> ); }; export default App;
JavaScript //Auth.js import React, { useContext } from "react"; import AuthContext from "./auth-context"; const Auth = () => { const auth = useContext(AuthContext); console.log(auth.status); return ( <div> <h1>Are you authenticated?</h1> {auth.status ? <p>Yes you are</p> : <p>Nopes</p>} <button onClick={auth.login}>Click To Login</button> </div> ); }; export default Auth;
Output
State Management in React In this example
- auth-context.js: Creates context with default values (status, login).
- App.js: Uses useState to manage authstatus and provides it through AuthContext.Provider.
- Auth.js: Uses useContext to access authstatus and login, showing login status and a button to trigger login
For more details follow this article => ReactJS useContext Hook
State Management With Redux
Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React. It makes easier to manage state and data. As the complexity of our application increases.
How Redux Works
- Store: The central place where all the app’s state is stored.
- Actions: Functions that describe changes to be made to the state.
- Reducers: Functions that handle actions and update the state based on them
Now let's understand this with the help of example
Install dependency to use Redux in your application
npm install redux react-redux
JavaScript // index.js import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import store from "./store"; import App from "./App"; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") );
JavaScript // App.js import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './actions'; function App() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); } export default App;
JavaScript // store.js import { createStore } from 'redux'; import counterReducer from './reducers'; const store = createStore(counterReducer); export default store;
JavaScript // reducers.js const counterReducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; export default counterReducer;
JavaScript // actions.js export const increment = () => { return { type: 'INCREMENT' }; }; export const decrement = () => { return { type: 'DECREMENT' }; };
Output
Redux example outputIn this example
- index.js: Renders App with Redux Provider to connect the store.
- App.js: Uses useSelector to access count and useDispatch to trigger increment and decrement actions.
- store.js: Creates the Redux store with counterReducer.
- reducers.js: Updates state based on INCREMENT and DECREMENT actions.
- actions.js: Defines increment and decrement action creators.
For more details follow this article => Introduction to React-Redux
Comparison of Hooks, Context API, and Redux
Below are the comparison between the state management hooks:
Hooks | Context API | Redux |
---|
Local state management in a component | Shared state across many components | Centralized state management in large apps |
Simple and easy to use | Simple but can become complex with large apps | More complex but powerful |
Optimized for local state | Good for medium-sized apps, can cause performance issues in large apps | Optimized for large apps with middleware |
Single component state | Passing data across deep component trees | Large-scale apps with many components needing to share state |
Inside the component | Global but only for specific contexts | Global store accessible from any component |
Conclusion
State management in React is crucial for handling and sharing data efficiently. useState is used for simple, local state, while useReducer manages complex state logic. The Context API helps share state across components without prop drilling, and Redux offers centralized state management for large applications. Each tool serves different needs, making React apps scalable and maintainable.
Similar Reads
State Management in React: Context API vs. Redux vs. Recoil
A fundamental idea in application development, State management is especially important for contemporary online and mobile apps, where dynamic, interactive user experiences necessitate frequent modifications to data and interface components. Fundamentally, it describes how an application maintains a
12 min read
Using the React Context API for Efficient State Management
The React Context API is a robust feature announced in React 16.3. It offers a way to share data within components without passing props directly at all stages. This is specifically useful for global data that many components seek to access, like user authentication, theme, or language settings. Rat
5 min read
State Management with useState Hook in React
useState is a built-in hook that empowers functional components to manage state directly, eliminating the need for class-based components or external state management libraries for simple use cases. It provides an easy mechanism to track dynamic data within a component, enabling it to React to user
3 min read
How to manage global state in a React application?
Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree. In this article, we will explore the following approac
7 min read
Introduction to Recoil For State Management in React
State Management is a core aspect of React development, especially as applications grow in size and complexity. While there are many libraries available to handle state, recoil has emerged as the fresh, modern approach that simplifies state management without the bloat of more complex systems like R
7 min read
Effect Management with useEffect Hook in React
useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability.
3 min read
Mastering State Management in ReactJS: A Beginner's Guide to the Context API
State Management in React.js is an essential topic as the whole of React counters & controllers work through their states. State is the initial value of the component, or the current value & using state management we can change the value by some specific functionalities using react.js. One s
10 min read
How to Use Redux Toolkit in React For Making API Calls?
In this article, we will explore how to use the Redux Toolkit in a React.js application to streamline state management and handle asynchronous operations, such as making API calls. Redux Toolkit's createAsyncThunk simplifies the creation of asynchronous action creators, allowing us to efficiently fe
4 min read
Simplifying State Management with Redux in MERN Applications
In this project, we've developed a todo web application utilizing the MERN stack (MongoDB, Express.js, React.js, Node.js) with Redux for state management. In this project, a todo can be created, viewed, and also saved in the database. Output Preview: Let us have a look at how the final output will l
6 min read
What are Action's creators in React Redux?
In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects. Action
4 min read