Are you tired of passing props down through multiple components, resulting in unnecessarily complex code? Look no further than useContext, a handy tool in React that allows you to access values from your state globally, without having to pass them down through every component in the tree. Think of it like a library bookshelf: you don’t have to carry every book with you everywhere you go, you can simply access them from the central location when you need them. In this article, we’ll show you how to use useContext and simplify your code in the process.
Using useContext starts with creating a context, where you can define the data you want to be available throughout your app. Imagine this context as the central heart of your application, pumping vital information to every component that needs it. With context created, components can simply declare their interest by accessing the data stored within. This prevents the tedious task of passing props through every component down the tree, and frees up your energy to focus on building robust, maintainable React applications.
Source www.youtube.com
What is useContext in React
UseContext in React is a feature that enables you to consume data from React Context API. It is a hook that allows child components to access values from their parent components without passing props from one component to another, making it an efficient way of sharing data across your application. UseContext eliminates the need of drilling props through multiple levels, thus reducing the complexity of the codebase. It is a great alternative to using the Redux library for state management.
How does useContext work?
UseContext relies on the Context API, which is a way to enable data sharing between components in React. Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user or a theme. Instead of passing props down to every level of your application, Context provides a way to share data between components without having to write code to pass props down to every level.
Creating a Context object
To use useContext, you will first need to create a context object using the createContext() function. The createContext() function returns an object that contains a Provider component and a Consumer component that can be used to share data between components. You can define the initial value of the context object in the createContext() function.
“`
import { createContext } from ‘react’;
const UserContext = createContext({
name: ‘Guest’,
email: ‘guest@example.com’
});
export default UserContext;
“`
In the example code above, we have created a UserContext object that has an initial value of {name: ‘Guest’, email: ‘guest@example.com’}. The createContext() function returns an object with Provider and Consumer components, which we can use in our application.
Using the Provider component to pass data down the component tree
You can use the Provider component to pass data down the component tree by setting a value prop that will be available to all child components that use the Consumer component. In the example below, we have created a UserProvider component that wraps the App component. The UserProvider component sets the value of the UserContext to {name: ‘John Doe’, email: ‘johndoe@example.com’}, which can be accessed by child components using the UserContext Consumer component.
“`
import React from ‘react’;
import UserContext from ‘./UserContext’;
import App from ‘./App’;
function UserProvider() {
const user = {name: ‘John Doe’, email: ‘johndoe@example.com’};
return (
);
}
export default UserProvider;
“`
Using the Consumer component to access data in child components
The Consumer component can be used in any child component to access the data passed from its parent components. In the example below, we are using the useContext hook to access the data from the UserContext object instead of using the Consumer component. Using the useContext hook, we can directly get the value of the context without rendering the Consumer component.
“`
import React, { useContext } from ‘react’;
import UserContext from ‘./UserContext’;
function Header() {
const user = useContext(UserContext);
return (
Welcome, {user.name}
Email: {user.email}
);
}
export default Header;
“`
The useContext hook takes the context object as its argument and returns the value passed from its nearest parent component.
Conclusion
The useContext hook provides a clean and efficient way to share data between components in React. By using Context, you can eliminate the need to pass props between components, making your code more readable and maintainable. You can use the createContext() function to create a context object, the Provider component to pass data down the component tree, and the Consumer component or the useContext hook to access the data in child components.
What is useContext?
useContext is a hook that is included in React 16.8. It allows you to consume a context object created by a parent component.
Context provides a way to share data between components without the need to pass it down through props. useContext hook makes it easier to access the context in child components.
Using useContext, we can avoid the problem of prop drilling. Prop drilling is where we pass data through multiple components to access it in a nested component.
Creating a Context object:
In order to use useContext, we need to create a context object. This is usually created in a parent component where the data is stored.
Here is an example:
“`javascript
const MyContext = React.createContext();
“`
This creates a context object called MyContext. We can now pass data into this context object and use it in any child component.
Using the useContext Hook:
Once we have created a context object, we can use the useContext hook in any child component that needs the data. This allows us to avoid prop drilling and access the data easily.
Example:
Assuming we have a parent component where we create the context object and pass data into it:
“`javascript
const MyContext = React.createContext();
function ParentComponent(){
const data = “Some data”;
return(
)
}
“`
Then, in a child component we can use the useContext hook to access the data:
“`javascript
const MyComponent = () => {
const data = useContext(MyContext);
return
{data}
;
}
“`
Multiple Context Objects:
It is possible to create and use multiple context objects in different parts of your application.
Creating Multiple Context Objects:
Creating multiple context objects is similar to creating one context object.
“`javascript
const MyContextOne = React.createContext();
const MyContextTwo = React.createContext();
function ParentComponent(){
const dataOne = “Some data”;
const dataTwo = “Some other data”;
return(
)
}
“`
Using Multiple Context Objects:
Using multiple context objects in a component is very similar to using one context object.
“`javascript
const MyComponent = () => {
const dataOne = useContext(MyContextOne);
const dataTwo = useContext(MyContextTwo);
return (
<>
{dataOne}
{dataTwo}
);
}
“`
By using useContext, we can easily consume context objects in our components and avoid the problem of prop drilling. This makes our code cleaner and more maintainable in the long run.