React’s useContext hook provides a way to easily pass data or states without manually passing the props down the component tree. The useContext hook is designed to share data that can be considered global data for a tree of React Components. Context can make a simple alternative to Redux when the data is simple or the application is small.
How the useContext() works:
In a React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (Example: local preference, UI theme, etc) that are required by many components within an application. Context helps us to share values like these between components without having to explicitly pass a prop through the entry-level of the tree.
How to use the useContext() Hook?
To use the context in React requires three simple steps. Creating the context, Providing the context, and Consuming the context.
- Create Context:
The built-in factory function createContext(default) creates a context instance.
- Context Provider:
Wrap child components in the Context.Provider and supply the state value.
Note: If you want to change the context value, simply update the value prop.
- Consuming the context:
Use the useContext(Context) React hook.
Here the hook makes sure to re-render the component when the context value changes.
You can have multiple users for a single context. When the context value changes all the users are notified and they are re-rendered. If the user is not wrapped inside the provider and tries to access the value of context then the value of the context would be the default value argument supplied to the createContext(defaultValue) factory function that had created the context.
When to use CONTEXT?
The idea to use components is to enable our components to access some global data and re-render when the global data is changed. This helps us remove the overhead of passing the data through props to the child components even if they are not required.
Context could be used for:
- Global State
- Application Config
- User Settings
- Preferred Language
The context in React is a concept that lets you supply child components with global data, no matter how deep they are in the components tree.
Using the context requires 3 steps: creating, providing, and consuming the context.
When integrating the context into your application, consider that it adds a good amount of complexity. Sometimes drilling the props through 2-3 levels in the hierarchy isn't a big problem.