The Context API in React provides a way to pass data through the component tree without the need to pass props down manually at every level. The global state created using context API can be accessed by any component within the tree, regardless of how close they are to one another in the hierarchy.
There are cases where we want to pass down data to a child component, and we have components in between the child component that needs such data and the parent component. Rather than do a prop drilling ( passing prop down to component that don't need it to get ut to components that need it )we can use a context API
When to Context API ?
- To avoid prop drilling which is a bad practice
- To avoid use a separate API for state management. Usually we will use library like Redux to manage our state, but in a medium or small size application context API would be the best choice.
How do we integrate Context API?
Create a file named context ( or whatever you want )
In that file import createContext from react like so;
Import { createContext, useContext} from 'react';Create a context:
const MyContext =
createContext();Create a provider:
const MyProvider = ({ children }) => {
const [state, setState] = useState(initialState);
return (
{children}
);
};
- Wrap your app with the provider in your index.JS file:
- Create an exported variable with that wraps your context with useContext making your context available to any component: const UseStateContext = () => useContext(MyContext); To use your created context in a file
Import your export context variable (UseStateContext) into your desired file.
Use it either by destructuring e.g
Const {state, setState} = UseStateContext();
Now you can use state and setState in your component
By following these steps, you have successfully integrated the Context API in your React application, allowing you to share state and functionality across components without prop drilling.
Note: Make sure to import the React
and useContext
hook from the react
package, and the useState
hook from the react
package or a compatible library like react-hooks
.
Top comments (0)