How to use react context and useContext hook
The React context provides data to components.The main reason behind context is to prevent prop drilling. When we need to send data componentA to ComponentC. We don't need to send props one to another component. We can direct get data from one to another. The context can br used to manage global data like global state, global theme & settings and more.
Today, you'll learn how to use the context in React.
There are three simple steps required to use context: creating the context, providing the context, and consuming the context.
A. Creating the context
import { createContext } from 'react'; const UserContext = createContext('Default Value');
createContext function accepts one optional argument: default value.
B. Providing the context
UserContext.Provider is used to provide context to child components.
To set the value of context use the value prop on the <UserContext.Provider value={value} />:
import { createContext } from "react"; import Greeting from "./Greeting"; const UserContext = createContext(); const AuthContext = createContext(); const App = () => { return ( <> <div className="App"> <h1>useContext Example</h1> <UserContext.Provider value={"Vivek Gupta"}> <AuthContext.Provider value={"authorised"}> <Greeting /> </AuthContext.Provider> </UserContext.Provider> </div> </> ); }; export default App; export {UserContext, AuthContext}
all the components that'd like later to consume the context have to be wrapped inside the provider component.
C. Consuming the context
UserContext.Consumer is used to consume context to child components.
import { UserContext, AuthContext } from "./App"; const Greeting = () => { return ( <> <UserContext.Consumer> {(name) => { return ( <AuthContext.Consumer> {(auth) => { return ( <h1>{`Welcome Mr ${name} . You are ${auth} to use Player of Code services`}</h1> ); }} </AuthContext.Consumer> ); }} </UserContext.Consumer> </> ); }; export default Greeting;
Output: Welcome Mr Vivek . You are authorised to use Player of Code services