0% completed
In this lesson, you'll learn about using the Context API and the useContext hook for global state management. You will explore step-by-step examples broken down to help you understand how it works better.
Let’s start by exploring a simple example of using the Context API to manage a theme (light or dark) across an application.
This is the first step is to create a context an give it a default value.
const ThemeContext = React.createContext('light');
Here, we've given the context a default value of 'light'.
Using the Provide component, we want to accept a value prop, which is usually the data or state you want to make available to the rest of your application.
function App() { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={theme}> <div> <h1>Current Theme: {theme}</h1> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> Toggle Theme </button> <ThemeDisplay /> </div> </ThemeContext.Provider> ); }
In this code example:
<h1>Current Theme: {theme}</h1>
renders the current theme dynamically.<ThemeDisplay />
is a separate component that can access the theme via ThemeContext.We can now use the useContext
hook to consume our created context:
function ThemeDisplay() { const theme = useContext(ThemeContext); return <div>The theme is currently: {theme}</div>; }
In this code, we accessed the ThemeContext
data using the useContext
hook by calling the 'theme' variable in any component we wish to use the theme toggling functionality.
.....
.....
.....