createContext
is a method provided by React's Context API that facilitates a way to pass data through the component tree without having to pass props down manually at every level. It's especially useful for passing down state, functions, or other data to deeply nested child components without prop drilling.
Here's a simple guide on how to use createContext
:
- Creating the Context
Firstly, you'll need to create a context.
import React, { createContext } from 'react';
const MyContext = createContext();
By default, createContext
accepts a default value, which will be used when a component doesn't have a matching Provider above it in the tree.
- Provider Component
Wrap the component tree with the Provider component, which accepts a value prop to be passed to consuming components.
const MyProvider = (props) => {
return (
<MyContext.Provider value={{ data: "Hello from context!" }}>
{props.children}
</MyContext.Provider>
);
};
- Consumer Component
There are two main ways to consume the value from the context:
- Using
MyContext.Consumer
:
function MyComponent() {
return (
<MyContext.Consumer>
{(value) => {
return <div>{value.data}</div>;
}}
</MyContext.Consumer>
);
}
- Using the
useContext
hook (more common and concise for functional components):
import React, { useContext } from 'react';
function MyComponent() {
const value = useContext(MyContext);
return <div>{value.data}</div>;
}
- Using the Provider
Wrap the parts of your app where you want the context to be accessible in the MyProvider
:
function App() {
return (
<MyProvider>
<MyComponent />
</MyProvider>
);
}
That's a simple overview of using createContext
in React. Remember that while the Context API is powerful, it doesn't mean you should use it everywhere. It's more apt for global state or shared utilities/functions that are needed across various components in your application. For local state or prop passing between a parent and a direct child, regular state and props work just fine.
Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.
Twitter: https://twitter.com/Diwakar_766
GitHub: https://github.com/DIWAKARKASHYAP
Portfolio: https://diwakar-portfolio.vercel.app/
Top comments (0)