Design system core
- React course
- Expert
- Lesson 26/32
- 5 min
Write a design system core with a theme and base components.
Design system core
In the second step you will write a ThemeProvider. This provider carries theme information to the whole app and shares it with createContext.
The starting code includes the previous Button solution; so the project grows in a single file. ThemeProvider keeps the theme with useState('light').
Child components read and change the theme with useContext.
Provider and value
ThemeProvider returns a ThemeContext.Provider. The value prop carries { theme, setTheme }; so children both read and change.
This pattern lets you share state without passing props through every layer. In a design system it is used for theme, language or cart state.
Even if the provider re-renders the value reference should stay stable.
Practice Write the ThemeProvider component
Write ThemeProvider. Import createContext and useState. Set ThemeContext = createContext(). Write function ThemeProvider({ children }). Keep theme and setTheme with useState('light'). Return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>. Export it.
Starter code
// Button.jsx
function Button({ variant, children }) {
const className = variant === 'primary' ? 'btn-primary' : 'btn-secondary';
return <button className={className}>{children}</button>;
}
export default Button;
// ThemeProvider.jsx
// Write the ThemeProvider component hereSample solution
import { createContext, useState } from 'react';
const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export default ThemeProvider;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: create a context
import { createContext, useState } from 'react';
const ThemeContext = ____();
import { createContext, useState } from 'react';
const ThemeContext = createContext();
Explanation: createContext creates a context.
2 What does ThemeProvider return?
- useState
- useEffect
- ThemeContext.Provider Correct answer
- Button
Explanation: ThemeProvider returns a Provider component.
3 Match provider concepts
| Term | Meaning |
|---|---|
createContext |
Creates a context |
Provider |
Shares the value |
value |
Theme and setter |
useContext |
Reads the value |