Context API is a way to pass data through the component tree without having to pass props down manually at every level. It is a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
In this article, we will see how to use Context API with a custom hook in React to manage the color mode of the application. Custom hooks make it easy to use context in a component.
Basic Example
Step 1: Create Context, Provider & Custom Hook
src/context/ColorModeContext.js
// context
const ColorModeContext = React.createContext('light');
// provider
export const ColorModeProvider = ColorModeContext.Provider;
// custom hook
export const useColorMode = () => {
const colorMode = useContext(ColorModeContext);
return colorMode;
}
Step 2: Wrap the app with the provider
import { ColorModeProvider } from "./context/ColorModeContext"
export default function App() {
return (
<ColorModeProvider>
<div>
// components
</div>
</ColorModeProvider>
);
}
Step 3: Use useColorMode
hook in you component
import { useColorMode } from './context/ColorModeContext';
export default function () {
const colorMode = useColorMode();
return <p> The Color mode is: {colorMode} </p>
}
Complex Example: setter function for color mode
Step 1: Create Context, Provider & Custom Hook
src/context/ColorModeContext.js
// context
const ColorModeContext = React.createContext();
// provider
export const ColorModeProvider({ children }) {
const [colorMode, setColorMode] = useState('light');
return (
<ColorModeContext.Provider value={{ colorMode, update: setColorMode}}>
{children}
</ColorModeContext.Provider>
);
}
// custom hook
export const useColorMode = () => {
const { colorMode, update } = useContext(ColorModeContext);
return { colorMode, update };
}
Step 2: Wrap the app with the provider
import { ColorModeProvider } from "./context/ColorModeContext"
export default function App() {
return (
<ColorModeProvider>
<div>
// components
</div>
</ColorModeProvider>
);
}
Step 3: Use useColorMode()
hook in a component
export default function() {
const { colorMode, update } = useColorMode();
const otherColorMode = colorMode === "light" ? "dark" : "light";
return (
<div>
<p>The color mode is: {colorMode}</p>
<button
onClick={() => {
update(otherColorMode);
}}
>
Set color mode to {otherColorMode}
</button>
</div>
);
}
That’s it! You have successfully implemented the Context API with a custom hook in React.