In this documentation, we'll guide you through setting up the React Context API for state management in a React application. We'll create a simple counter application to demonstrate how to use the Context API to share state between components.
- Open your terminal or command prompt.
- Run the following command to create a new project using Vite:
npm create vite@latest- Enter the desired project name when prompted (e.g.,
my-react-context-app). - Choose a package manager (npm or yarn) for the project.
- Select
reactas the framework for the project. - Choose
javascriptas the language for the project. - Once the project is created, navigate to the project directory using the following command:
cd my-react-context-app- Install the necessary Node.js packages for the project by running the following command:
npm install- Start the development server by running the following command:
npm run dev- Your React application will be served at the specified localhost address, typically
http://localhost:3000.
- Navigate to the root directory of your project which is inside the
srcfolder. - Create a folder named
components.
- Inside the
srcfolder, Go to the file namedApp.jsx. - This file will serve as the main component of your application.
- We will make the files further in the project which is included in the
App.jsxfile
import { useState } from 'react';
import './App.css';
import Counter from './Counter';
import { useContext } from 'react';
import { counterContext } from '../context/ContextCounter';
function App() {
// Access the counterContext using useContext hook
const counterState = useContext(counterContext);
// Log the context value to the console for debugging
console.log("Context", counterState);
return (
<div className='app'>
<h1>Context API in ReactJS</h1>
{/* Display the current count */}
<h4>Count is {counterState.count}</h4>
{/* Render the Counter component multiple times */}
<Counter />
<Counter />
<Counter />
<Counter />
</div>
);
}
export default App;Explanation:
useState:useStateis a hook in React that allows functional components to manage state. We're not using it here directly, but we're importing it as a standard practice in React applications.Counter: TheCountercomponent is imported and rendered multiple times in theAppcomponent. This component will display buttons to increment and decrement the count.useContext:useContextis a hook in React used to access the context value. We use it here to access thecounterContext.counterContext:counterContextis a context object created usingcreateContextin theContextCounter.jsxfile. It provides a way to share the counter state across different components.
- Inside the
srcfolder (root directory), create a folder namedcontext. - This folder will contain files related to the Context API.
- Inside the
contextfolder, create a file namedContextCounter.jsx. - This file will define the context and provider for the counter state.
import React, { createContext, useState } from 'react';
// Create a context object
export const counterContext = createContext(null);
// Define provider component
export const CounterProvider = (props) => {
// Define counter state
const [count, setCount] = useState(0);
return (
// Provide counter state value and setter function to the context provider
<counterContext.Provider value={{ count, setCount }}>
{props.children}
</counterContext.Provider>
);
};Explanation:
createContext:createContextis a function provided by React to create a new context object. It creates a context object namedcounterContextin this case.CounterProvider:CounterProvideris a provider component responsible for providing the counter state to its children components. It wraps its children withcounterContext.Providerand makes the counter state available to them.useState:useStateis used inside theCounterProvidercomponent to define the counter state (count) and its setter function (setCount). It initializes the count state with a default value of0.
- Inside the
componentsfolder, create a file namedCounter.jsx. - This file will contain the
Countercomponent responsible for displaying and updating the count.
import React from 'react';
import { useContext } from 'react';
import { counterContext } from '../context/ContextCounter';
function Counter() {
// Access the counterContext using useContext hook
const CounterContext = useContext(counterContext);
return (
<div>
{/* Button to increment count */}
<button onClick={() => CounterContext.setCount(CounterContext.count + 1)}>Increment</button>
{/* Button to decrement count */}
<button onClick={() => CounterContext.setCount(CounterContext.count - 1)}>Decrement</button>
</div>
);
}
export default Counter;Explanation:
CounterContext:CounterContextis the context object obtained using theuseContexthook. It contains the current count (count) and the setter function (setCount) to update the count.useContext:useContextis used to access the context value. Here, it is used to access thecounterContextobject defined inContextCounter.jsx.counterContext:counterContextis imported from theContextCounter.jsxfile. It provides access to the counter state and setter function across different components.
- In the root directory of your project, locate the entry point file (
main.jsxorindex.js). - Update the entry point file to initialize the React application with the context provider.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import './index.css';
import { CounterProvider } from './context/ContextCounter';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
{/* Wrap the App component with CounterProvider */}
<CounterProvider>
<App />
</CounterProvider>
</React.StrictMode>,
);Explanation:
CounterProvider:CounterProviderwraps theAppcomponent with theCounterProvidercomponent. This ensures that the counter state is available to all components within theCounterProvidercomponent.ReactDOM.createRoot:createRootis a method provided byReactDOMfor creating a root-level element for rendering React components. Here, it renders theAppcomponent wrapped withCounterProviderinside the root element with the idroot.