What is useContext hook in react
Posted 3 years ago by Ryan Dhungel
Category: React Hooks
Viewed 2987 times
Estimated read time: 8 seconds
- You can create context using
React.createContext
such as constThemeContext = React.createContext()
Once created, you will provide it to the components using
<ThemeContext.Provider>
useContext hook >
useContext(MyContext)
accepts object/value returned fromReact.createContext
A component calling useContext will always re-render when the context value changes
Background color toggle app using context value
Try this example. This will allow you to change the background color of your page by accessing value from context:
import React, { useContext, useState, useEffect } from "react";
// theme object
const themes = {
red: "#ff0000",
green: "#00ff00"
};
// create context
const ThemeContext = React.createContext(themes);
// provide context to components
const App = () => {
return (
<ThemeContext.Provider value={themes}>
<Home />
</ThemeContext.Provider>
);
};
const Home = () => {
const themes = useContext(ThemeContext);
const [toggle, setToggle] = useState(false);
useEffect(() => {
console.log(themes);
// value of toggle in the state is true or not?
document.body.style.backgroundColor = toggle ? themes.green : themes.red;
}, [toggle]); // run useEffect when value of toggle changes
// on button click set toggle state
return <button onClick={() => setToggle(!toggle)}>Switch color</button>;
};
export default App;
Example of updating react context from child components
import React, { useContext, useState } from "react";
// create a context with default value of string and function
const UserContext = React.createContext({
name: "",
setName: f => f // () => {}
});
// provide context to components
const App = () => {
// state
const [name, setName] = useState("");
// destructure both the state value (language) and state set method (setLanguage)
// to send down value using context provider to context consumer/components
const value = { name, setName };
// provide context to child components
return (
<>
{name && <p>Your name is: {name}</p>}
<UserContext.Provider value={value}>
<UserForm />
</UserContext.Provider>
</>
);
};
// component with its own state for handling form data
// it also has access to parent state (name) and methods (setName)
const UserForm = () => {
const { name, setName } = useContext(UserContext);
const [typedName, setTypedName] = useState("");
const resetName = () => {
setName("");
setTypedName("");
};
return (
<div>
<input
type="text"
onChange={event => setTypedName(event.target.value)}
value={typedName}
/>
<button onClick={() => setName(typedName)}>
Click here to show name in parent component
</button>
<button onClick={resetName}>Reset</button>
</div>
);
};
export default App;