Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Using the React Context API for Efficient State Management
Next article icon

State Management in React – Hooks, Context API and Redux

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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; 



usestate
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

Animation22
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

Animation23
Redux example output

In 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.


Next Article
Using the React Context API for Efficient State Management

S

souravsharma098
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Redux
  • React-Hooks
  • ReactJS-State

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences