How to Use the React Context API ?

How to Use the React Context API ?

Common way to manage state by passing props to components. Passing props parent to child components.

if you want to pass same data to lots of components or when components are far away from each other than it's causes optimization and performance issue.

Context API allows data to be passed through a component tree without having to pass props manually at every level. This makes it easier to share data between components.

1. Create Context

create a context object using the create Context function from the 'react' 

Context API to provide props all over application

2. Wrap Component With context Provider

Now create context object, and wrap the components that need access to the shared data with a Provider component.

Provider component accepts a "value" prop that holds data,

Context provider reactjs API

3. Consume the context

Now consume the context in components. To do this, we use the "useContext" hook from React.

Consume context value from provider in reactjs

All code in one place

Context API example in Reactjs

Previous Post Next Post