Introduction to Context API
The Context API is a way to share data between components in a React application without passing props down manually. It provides a way to share values between components without having to explicitly pass them down through props.
Creating a Context
To create a context, you use the `createContext` function from the `react` module.
import { createContext } from 'react';const ThemeContext = createContext();
In this example, we create a `ThemeContext` using the `createContext` function.
Providing a Context
To provide a context to a component, you use the `Provider` component.
import React from 'react';
import { ThemeContext } from './theme-context';function App() {
return (
<ThemeContext.Provider value={{ theme: 'dark' }}>
<Toolbar />
</ThemeContext.Provider>
);
}In this example, we provide the `ThemeContext` to the `Toolbar` component.
Consuming a Context
To consume a context, you use the `useContext` hook.
import React, { useContext } from 'react';
import { ThemeContext } from './theme-context';function Button() {
const theme = useContext(ThemeContext);return (
<button style={{ backgroundColor: theme.theme }}>
Click me!
</button>
);
}In this example, we consume the `ThemeContext` in the `Button` component.
Updating a Context
To update a context, you can use a state management solution like Redux or MobX.
import React, { useState } from 'react';
import { ThemeContext } from './theme-context';function App() {
const [theme, setTheme] = useState('dark');return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}In this example, we update the `ThemeContext` using the `useState` hook.
Example Code
Here's an example of a simple React app that uses the Context API:
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('dark');return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);return (
<div>
<Button />
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Toggle theme
</button>
</div>
);
}function Button() {
const { theme } = useContext(ThemeContext);return (
<button style={{ backgroundColor: theme }}>
Click me!
</button>
);
}
Here's a practice exercise:
Create a simple React app that uses the Context API to share a user's authentication status between components.
Hint: Use the `createContext` function to create a context, and the `useState` hook to store the user's authentication status.