Introduction
In this article, you will examine how to implement Context API and the React Hook useContext()
in your React project. The Context API is a React structure that allows you to share specific data from all levels of your application and aids in solving prop-drilling.
React Hooks
are functions that serve as a modular replacement for state and lifecycle methods written in functional components. The useContext()
method is an alternative to prop-drilling through the component tree and creates an internal global state to pass data.
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 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!
Conclusion
The Context API in React provides you with built-in functions and components to avoid prop-drilling in your component tree. The React Hook useContext()
applies the same functionality in a streamlined, functional component body in one call.
Your feedback matters!
If you like my blog and you would like to encourage me in writing more often, please clap, share and comment. Your interest is the best motivation to share my thoughts.
Thank you for reading! Happy coding♥️