This page will give you some code examples of how to use React Context in different scenarios, including function and class components and TypeScript.
If you're new to React Context, I recommend you check out my other article on the topic, which explains it more in detail. I like to think of this page as a "TLDR" of React Context for when I need it in the future.
Functional components
Create the Context
const ThemeContext = createContext({ dark: false });
Create a provider
After creating the Context, we need to wrap the code that will access the data from it in a provider.
import React from 'react';
import ThemeContext from '../context/ThemeContext';// ...
export const App = () => {
// ...
return (
<ThemeContext.Provider value={{ dark: false, toggleDark: () => console.log('toggle'), }} > <ToggleDarkMode />
{/*...*/}
</ThemeContext.Provider> );
};
Consume the Context
const ToggleDarkMode = () => {
const { dark, toggleDark } = useContext(ThemeContext); const handleOnClick = (e) => {
e.preventDefault();
toggleDark();
};
return (
<>
<h1>{dark ? "🌙" : "🌞"}</h1>
<button onClick={handleOnClick}>Toggle dark mode</button>
</>
);
};
Class components
Create a Context and provider
Creating and providing the Context in class components works exactly the same as we saw in function components above.
Consume the Context
import ThemeContext from '../context/ThemeContext';
// ...
export class ToggleDarkMode extends React.Component {
static contextType = ThemeContext;
// ...
}
When a Context type is defined, React will assign the chosen Context to this.context
.
export default class ToggleDarkMode extends React.Component {
static contextType = ThemeContext;
// ...
render() {
const { dark, toggleDark } = this.context;
// ...
}
}
TypeScript
You can check out this codepen for an example of how to use React Context with TypeScript.
To make our code TypeScript-compatible, we don't need to change nearly anything. In fact, if we provide default values for everything, we don't need to change anything at all since TypeScript will automatically infer the type.
If we don't want to provide all default values, we can create an interface and use that when creating the Context:
interface IThemeContext {
dark: boolean;
toggleDark?: () => void;
}
const ThemeContext = createContext<Partial<IThemeContext>>({});
Projects related to React Context
In this section, I compiled a list of links and projects that use React Context, so that you can learn by example.
An interactive example on codepen of how to use React Context for changing a website's theme.
A collection of relevant links related to React Context hosted on GitHub.
How to use React Context with TypeScript
Here I explain how to use React Context and how to make it compatible with TypeScript.
Am I missing anything? Let me know in the comments, or send me an email!