How to create context API ?
Step 1: First, you need to create a context object using the createContext function from the ‘react’ library. This context object will hold the data that you want to share across your application.
Javascript
import { createContext } from 'react' ; export const MyContext = createContext( "" ); |
Step 2: Once you’ve created a context object, you need to wrap the components that need access to the shared data with a Provider component. The Provider component accepts a “value” prop that holds the shared data, and any component that is a child of the Provider component can access that shared data.
Javascript
// Create a parent component that wraps child components with a Provider import { useState, React } from "react" ; import { MyContext } from "./MyContext" ; import MyComponent from "./MyComponent" ; function App() { const [text, setText] = useState( "" ); return ( <div> <MyContext.Provider value={{ text, setText }}> <MyComponent /> </MyContext.Provider> </div> ); } export default App; |
Step 3: Now that we’ve created the provider component, we need to consume the context in other components. To do this, we use the “useContext” hook from React.
Javascript
import { useContext } from 'react' ; import { MyContext } from './MyContext' ; function MyComponent() { const { text, setText } = useContext(MyContext); return ( <div> <h1>{text}</h1> <button onClick={() => setText( 'Hello, world!' )}> Click me </button> </div> ); } export default MyComponent; |
What are Provider and Consumer in the Context API ?
Context API is a term that is created to pass as a global variable and can be accessed anywhere in the code. It is another way to pass props from child to parent i.e. known as “prop drilling“. It has two main components “The Context Provider ” and “The Context Consumer“.
Table of Content
- The Context Provider
- The Context Consumer
- How to create context API ?
- Conclusion