![]() |
VOOZH | about |
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.
Table of Content
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).
const Context = useContext(initialValue);Steps to create the React application:
Step 1: Create React Project
npm create-react-app myreactappStep 2: Change your directory and enter your main folder charting as
cd myreactappProject Structure:
Choosing the right state management solution is crucial for your applicationโs scalability.
Example: In this example, App.js is sending data to component ComC with the help of useContext.
Step to run the application:
Open the terminal and type the following command.
npm startOutput: Open the browser and our project is shown in the URL http://localhost:3000/
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.
Step to install Redux: Use this command in project directory
npm i @reduxjs/toolkit react-reduxProject 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.
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/
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. |