React Context
React Context
Rect Context
React Context is a powerful feature that allows you to manage state across your entire application without having to pass props down manually at every level of the component tree.
Here are the basic steps to use React Context:
Step 1: Create the Context
First, you need to create the context. You’ll need to export it from a file so that your components can use it. createContext
function takes a value as initialValue. If there is no context provider, the default value will be used.
CounterContext.js
1 | import { createContext } from "react"; |
Here we provide a default object { count: 0, setCount: (v) => {} }
for the CounterContext.
Step 2: Use the Context
useContext
is a React Hook that lets you read and subscribe to context from your component.
ChildComponent.js
1 | import { useContext } from "react"; |
If you don’t provide the Context, the default value will be used. in this case, the count
value and setCount
function from the CounterContext will be used.
Step 3: Provide the Context
Provide the context.
App.js
1 | import { useState } from "react"; |
Here we provide the Context and give the value { count, setCount }
created from useState
Hook.
Conclusion
React Context provides a clean and efficient way to manage state in your React applications. By creating a context provider, you can encapsulate your state logic and make it accessible to any component in your application without the need for prop drilling. Understanding these basic concepts will empower you to build more complex and interactive applications using React. Happy coding!
References: