The Wayback Machine - https://web.archive.org/web/20240906114626/https://www.geeksforgeeks.org/whats-the-difference-between-usecontext-and-redux/
Open In App

What’s the difference between useContext and Redux ?

Last Updated : 12 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In React, useContext and Redux both approaches provide ways to manage and share state across components. Both work and manage global data to share and access from any component present in the application DOM tree, but they have different purposes and use cases.

useContext

useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component. It is designed to share data that can be considered global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes).

Syntax:

const Context = useContext(initialValue);

Steps to create the React application:

Step 1: Create React Project

npm create-react-app myreactapp

Step 2: Change your directory and enter your main folder charting as

cd myreactapp

Project Structure:

Example: In this example, App.js is sending data to component ComC with the help of useContext.

Javascript




// filename - App.js
 
import React, { createContext } from "react";
import "./index.css";
import ComB from "./ComB";
 
const Data = createContext();
 
export default function App() {
    return (
        <div className="App">
            <Data.Provider value={"Welcome to GFG"}>
                <ComB />
            </Data.Provider>
        </div>
    );
}
 
export { Data };


Javascript




// Filename ComB.js
 
import React, { useState } from "react";
import ComC from "./ComC";
 
const ComB = () => {
    const [show, setShow] = useState(false);
    return (
        <>
            {show ? <ComC /> : null}
            <button onClick={() => setShow(!show)}>
                Click ME
            </button>
        </>
    );
};
 
export default ComB;


Javascript




// Filename ComC.js
 
import React, { useContext } from "react";
import { Data } from "./App";
 
const ComC = ({ name }) => {
    const context = useContext(Data);
    return <h1>{context}</h1>;
};
 
export default ComC;


Step to run the application:

Open the terminal and type the following command.

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

Redux

Redux is a state managing library used in JavaScript apps. It is very popular for React and React-Native. It simply manages the state and data of your application.

Building Parts of Redux

  • Action: Actions are JavaScript object that contains information. Actions are the only source of information for the store.
  • Reducer: Reducers are the pure functions that contain the logic and calculation that needed to be performed on the state.
  • Store: Store is an object which provides the state of the application. This object is accessible with help of the provider in the files of the project.

Step to install Redux: Use this command in project directory

npm i @reduxjs/toolkit react-redux

Project Structure:

Depemndencies list after installtin redux in package.json

{
"name": "myreactapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@reduxjs/toolkit": "^1.9.7",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.1.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}

Example: In this example, we have created two buttons one will increment the value and another will decrement the value. With Redux, we are managing the state.

Javascript




// filename - App.js
 
import React from "react";
import "./index.css";
import { useSelector, useDispatch } from "react-redux";
import { incNum, decNum } from "./actions/index";
 
function App() {
    const mystate = useSelector((state) => state.change);
    const dispatch = useDispatch();
 
    return (
        <>
            <h2>
                Increment/Decrement the number using Redux.
            </h2>
            <div className="app">
                <h1>{mystate}</h1>
                <button onClick={() => dispatch(incNum())}>
                    +
                </button>
                <button onClick={() => dispatch(decNum())}>
                    -
                </button>
            </div>
        </>
    );
}
 
export default App;


Javascript




// actions/index.js
 
export const incNum = () => {
    return { type: "INCREMENT" };
};
 
export const decNum = () => {
    return { type: "DECREMENT" };
};


Javascript




// reducers/func.js
 
const initialState = 0;
 
const change = (state = initialState, action) => {
    switch (action.type) {
        case "INCREMENT":
            return state + 1;
        case "DECREMENT":
            return state - 1;
        default:
            return state;
    }
};
 
export default change;


Javascript




// Filenme - reducers/index.js
 
import change from "./func";
import { combineReducers } from "redux";
 
const rootReducer = combineReducers({ change });
 
export default rootReducer;


Javascript




// Filename - store.js
 
import { createStore } from "redux";
import rootReducer from "./reducers/index";
 
const store = createStore(
    rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
        window.__REDUX_DEVTOOLS_EXTENSION__()
);
 
export default store;


Javascript




// Filename - index.js /src directory
 
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App.jsx";
import store from "./store";
import { Provider } from "react-redux";
 
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root")
);


Step to run the application: Open the terminal and type the following command.

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

Difference between useContext and Redux

useContext 

Redux

useContext is a hook. Redux is a state management library.
It is used to share data. It is used to manage data and state.
Changes are made with the Context value. Changes are made with pure functions i.e. reducers.
We can change the state in it. The state is read-only. We cannot change them directly.
It re-renders all components whenever there is any update in the provider’s value prop. It only re-render the updated components.
It is better to use with small applications. It is perfect for larger applications. 
It is easy to understand and requires less code. It is quite complex to understand.


Similar Reads

How does useContext help with sharing data between components in React?
useContext is a hook in React that facilitates the sharing of data between components without the need to pass props manually through every level of the component tree. It allows components to consume data from a context that has been defined higher up in the component hierarchy. How does it work?Centralized Data Storage:React context allows you to
3 min read
In what scenarios might you choose Redux Thunk over Redux Saga, and vice versa?
Redux, a predictable state container utilized in JavaScript applications, is extensively employed in React applications to manage application state. Middleware libraries like Redux Thunk and Redux Saga are commonly integrated with Redux to handle side effects such as asynchronous API calls and intricate state transitions. While both offer solutions
4 min read
Why Redux Toolkit is preferred over Redux ?
While working as a Front-end Developer or Full Stack Developer, many engineers encountered Redux. But Recently Redux Team launched Redux Toolkit(RTK), an officially recommended SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development proce
4 min read
Redux Toolkit Better way to write Redux code in ReactJS
Redux Toolkit is used for writing redux code but in a more concise way. Redux Toolkit (RTK) solves three bigger problems that most of the developer's face who used redux in a react application. Too much code to configure the store.Writing too much boilerplate code to dispatch actions and store the data in the reducer.Extra packages like Redux-Thunk
4 min read
Benefits of using React-Redux over plain Redux
React-Redux streamlines state management in React applications by integrating seamlessly with Redux, eliminating prop drilling. It enhances predictability and scalability through centralized state management and facilitates the creation of reusable UI components. This integration optimizes syntax, approaches, and implementation steps, offering a ro
5 min read
Redux Thunk vs. Redux Saga: Choosing the Right Middleware
Redux, a predictable state container for JavaScript apps, is widely used in React applications for managing application state. Redux Thunk and Redux Saga are middleware libraries commonly employed with Redux for managing side effects such as asynchronous API calls, complex state transitions, and more. Both offer solutions for handling asynchronous
3 min read
How Redux Toolkit simplifies Redux code in React application ?
Redux Toolkit is a powerful library designed to simplify the complexities of managing application state with Redux in React applications. At its core, Redux Toolkit provides developers with a set of utilities and abstractions that significantly reduce boilerplate code and streamline common Redux tasks. This means that developers can focus more on b
5 min read
How does Redux Saga Differ from Redux Thunk ?
In Redux, middleware plays a crucial role in managing asynchronous actions. Redux Saga and Redux Thunk are two popular middleware libraries used for handling side effects in Redux applications. While both serve similar purposes, they differ significantly in their approach and capabilities. In this article, we'll see the differences between Redux Sa
5 min read
How does Redux Toolkit simplify Redux development?
Redux is a powerful state management library for JavaScript applications, but setting it up and managing boilerplate code can be cumbersome. Redux Toolkit is an official package from the Redux team designed to streamline Redux development and reduce boilerplate code. In this article, we'll explore how Redux Toolkit simplifies Redux development and
6 min read
How to Migrate an Existing Redux Application to Redux Toolkit?
Migrating an existing Redux application to Redux Toolkit (RTK) can streamline your Redux code, reduce boilerplate, and improve maintainability. Here's a step-by-step guide to help you through the migration process. Prerequisites:ReduxReactJSJavaScriptSteps to Create Redux ApplicationStep 1: Create a React Application named 'redux-migration-demo' an
4 min read
ReactJS useContext Hook
Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes). Context API u
2 min read
Purpose of the useContext hook
The useContext hook in React makes it easier for components to get data from the overall theme or settings of your app. In React, "context" is like a way to share information among different parts of your app without having to hand it down through each piece. So, useContext helps a component quickly grab that shared info and use it. Purpose of useC
2 min read
What's the role of the useContext hook in React Hooks?
The useContext hook in React Hooks allows you to consume values from the React context without needing to explicitly pass props through every level of your component tree. Role of useContext hook in React Hooks:Accessing Context Values:With useContext, you can access values stored in a React context from any component within the same context provid
2 min read
Context API with useContext Hook
React Context API is a very helpful feature that enables the sharing of state across components without the need for prop drilling. It simplifies state management and makes it easier to pass data down the component tree. In this article we will explore the Context API and demonstrate how to use it with the "useContext" hook through practical exampl
3 min read
How to combine useContext with useReducer?
Combining useContext with useReducer in React allows you to manage a global state more effectively by providing a centralized state management solution. How to combine useContext with useReducer?Create a Context: First, you need to create a context to hold your global state and provide it to your component tree. You can use the React.createContext(
3 min read
Implementing Global State Management with useContext
The useContext hook is a powerful addition introduced in React 16.8. It allows you to share context (or some value) with all the child elements within a context provider. This is particularly useful when you want to access data or state in child components without manually passing props down to each nested component. In this article, you'll learn a
4 min read
How to implement useContext Hook in a Functional Component ?
In React, the useContext hook is used to consume values from a context. Context in React is a way to share values like themes, authentication status, or any other global state between components without explicitly passing the props through each level of the component tree. Syntax of useContext Hook:const authContext = useContext(initialValue);Steps
2 min read
How can you use useContext to consume values from a React context?
ReactJS provides Context API to manage the state at a global level in your application. It acts as a container where you can store multiple states, and functions and access them from anywhere in the application by using the useContext hook. In this article, we are going to learn how to use the useContext hook with examples and syntax. What is useCo
3 min read
What is the difference between Component and Container in Redux ?
Redux is a state management library for JavaScript applications that helps to store and manage the state of an application in a single store, making it easier to maintain and update the state as the application grows. In this article, we will learn about Component &amp; Container in Redux, along with discussing the significant distinction that diff
4 min read
What are the differences between Redux and Flux in ReactJS ?
During the phase of applications or software development, we gather the requirements of customers to create a solution to solve the problem of customers or businesses. To solve problems we rely on different technologies and architecture patterns. for a long time, developers were using MVC (Model-View-Controller) pattern. As we know that after every
10 min read
Explain The Benefits And Challenges Of Caching And Offline Support in Redux
When web applications become complex or users expect more from them, efficient data handling mechanisms like caching and offline support become the need of the hour. Caching can be used to store data locally and avoid the requirement to fetch data from a network every time. Offline support allows the user to interact with the application even when
5 min read
Redux and The Flux Architecture
Flux Architecture: Flux is AN architecture that Facebook uses internally when operating with React. It is not a framework or a library. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow. Redux is a predictable state container for JavaScript apps. Redux is a state-management tool that
5 min read
Introduction to Redux (Action, Reducers and Store)
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.Uses: It makes easier to manage state and data. As the complexity of our application increases. At the start, it is hard to understand bu
4 min read
Comparing Redux and Context API in React: A Comprehensive Analysis
In this article, we are going to learn about the difference between the Redux and Context APIs. We will cover each of them entirely with their live examples, and then we will cover the differences between them. Table of Content Context APIReduxDifference between Redux and Context APIConclusionContext APIInstead of manually passing props down at the
5 min read
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building. We will discuss the following state management technique
6 min read
Presentational and Container Components in React Redux
React Redux is a library that simplifies state management in React applications by providing a centralized store where data can be stored and accessed from any component. It helps keep your code organized and efficient, especially in large-scale projects where the managing state becomes more complex. With React Redux, you can easily connect your Re
2 min read
React Redux Interview Questions And Answers
Redux is one of the most popular state management libraries used today for building a complex application that requires global state management. In this article, you will learn the top Redux interview questions and answers that are most frequently asked in interviews. Before proceeding to learn Redux interview questions and answers, it is beneficia
15+ min read
Explain the benefits and limitations of SSR in Redux applications.
SSR in Redux applications means rendering React components on the server side instead of the client's browser. This helps to speed up initial page loads and ensures that search engines can better understand and index your content. With SSR, users get a faster and more seamless experience when accessing your website or application. Benefits of SSR i
2 min read
Explain the benefits and challenges of infinite scrolling in Redux.
Infinite scrolling in Redux means automatically loading more content as you scroll down a webpage or application. Redux manages the state of the content, making sure it's seamless and efficient for users. Benefits of Infinite Scrolling in Redux:To Enhance User Experience: Infinite scrolling provides a seamless browsing experience for users by loadi
2 min read
Explain the role of middleware in authentication and authorization in Redux.
Middleware is a major element in the management of authentication and authorization in Redux applications. It acts as a barrier between actions and reducers, enabling users to intercept actions and enforce security measures. This ensures that only authorized users with appropriate permissions can access certain features or perform specific actions
2 min read