What is Context API?
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Since release 16.3, React has had a stable version of Context API that can be used to easily share data across multiple components. It can be passed directly to the components that need it, thus preventing props drilling.
Check out the documentation on Context
Why use Context API?
Context is mainly used when you want simple state management. Context makes you avoid props drilling. In Context, you make the parent component a provider and define the child as a consumer that directly uses props from the parent rather than the passing of props through each child component that leads up to the component where it is needed
Basic example demonstrating usage
You can use context by:
- Creating the context
First, create a new project with create-react-app.
npx create-react-app react-context-app
When the project is ready, we have to create a few files.
src/context/main.js
src/component/main.js
React Context is initialized with React.createContext top-level API
import React, { createContext } from 'react';
const AppContext = createContext();
createContext
is used to initialize the React Context. It creates the context object with the Provider and Consumer component. It takes in a default value which can only be used when a component does not have a matching Provider above its tree
- Providing the value of the context to the application
// src/context/main.js
import React, { createContext, useState } from "react";
const AppContext = createContext();
const AppContextProvider = ({ children }) => {
let [state, setState] = useState({
name: "Jane Doe",
age: 20
});
const incrementAge = () => {
setState(prevState => ({
...prevState,
age: state.age + 1
}));
};
const decrementAge = () => {
setState(prevState => ({
...prevState,
age: state.age - 1
}));
};
return (
<AppContext.Provider value={{ state, incrementAge, decrementAge }}>
{children}
</AppContext.Provider>
);
};
export { AppContext, AppContextProvider };
- consuming the value
// src/component/main.js
import React, { useContext } from "react";
import { AppContext } from "../context/main";
const AppComponent = () => {
const { state, incrementAge, decrementAge } = useContext(AppContext);
return (
<>
<div>My name is {state.name}</div>
<div>my age is {state.age}</div>
<button onClick={incrementAge}>+1</button>
<button onClick={decrementAge}>-1</button>
</>
);
};
export default AppComponent;
In your App.js
add the Provider to the app by wrapping it around the AppComponent
// src/App.js
import React from "react";
import { AppContextProvider } from "./context/main";
import AppComponent from "./component/main";
function App() {
return (
<AppContextProvider>
<AppComponent />
</AppContextProvider>
);
}
export default App;
Voila!
Top comments (6)
Thanks for sharing this. It was super helpful.
Oh wow, thanks a lot for this.
The article was very easy to understand, I'll try it in my project for sure.
this was super helpful as my states quickly got out of hand with a big form. Context + hooks is just so delightful to use.
Thank you! 😁
Nice and straight to the point. It eems hooks made the context API a lot easier to use because the last time I tried to use it, I didn't like what I saw. Thanks Odunayo
Thanks a lot
Thank you :)