![]() |
VOOZH | about |
Context API in React provides a way to share data globally across components without prop drilling. It allows creating a lightweight global state accessible by any component.
Context API prevents prop drilling by providing global state accessible anywhere, simplifying state management and improving performance.
To work with Context API we need React.createContext(). It has two properties Provider and Consumer. The Provider acts as a parent it passes the state to its children whereas the Consumer uses the state that has been passed.
Follow these steps to create and use Context API in a React application.
Step 1: Create a React application using the following command.
npx create-react-app context-api-demoStep 2: After creating your project folder(i.e. project), move to it by using the following command.
cd context-api-demoStep 3: We will create two new files one is Context.js to create our context and another file named as WelcomePage.js for creating a component that will consume the context.
It will look like this:
👁 Project StructureThe Context API is used to share user data (name and ID) across components without prop drilling.
Example: Write the following code in respective files:
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output:
Context API is simpler, maintains one-way data flow, and allows multiple stores compared to Redux’s single store.