Context API is a feature in ReactJS that is often used as a replacement for Redux or other state management libraries because it allows for simpler data flow in an application.
Here is how it can be used:
1. Create Context: First step is to create a context.
```
const MyContext = React.createContext(defaultValue);
```
The defaultValue argument is only used when a component does not have a matching Provider.
1. Create Context Provider: To pass the data through the component tree, create a context provider. All the components that are children of this provider will have access to the context.
```
```
The provider accepts a `value` prop to be passed to consuming components that are descendants of this Provider.
1. Consume Context: After provider is set, we can access the value in any child component by using the `React.useContext()` hook.
```
const contextValue = React.useContext(MyContext);
```
Or you can use the `Context.Consumer` component.
```
```
Context API is primarily used when some data needs to be accessible by many components at different nesting levels.
Here is a complete example using the Context API in React:
```
import React, { createContext, useState } from ‘react’;
// Step1: create your context
const NumberContext = createContext();
const App = () => { // we pass this value down the component tree using provider const [number, setNumber] = useState(0);
return (const Display = () => { const { number } = useContext(NumberContext);
returnconst Increment = () => { const { number, setNumber } = useContext(NumberContext);
return }export default App;
```
We created a basic counter with a display and increment button where state is shared between the two components using Context API. Notice how easy it is to share state and change it from different components.