Posts > Learning React Context API
September 10, 2023
Context Provider and Context ConsumerπLess prop drilling ( passing props down manually at every level )
value props, which is the data you want to share<MyContext.Provider value={` your data / state `} />
{/* child components */}
</MyContext.Provider>πtypically you want to wrap your top-level component or a higher-level component with the context provider to make the data available to all its children components. Such as App.jsuseContext hooksimport { useContext } from 'react';
const myData = useContext(myContext);πwhere does themyContextcomes from? what arguments doesuseContextneeded?
Well themyContextis created usingcreateContextin which we needed to pass into ouruseContextas a default data. TheuseContextaccepts any kind of value ( even an object ).
import { createContext } from 'react';
export const myContext = createContext(/* any value ( even object )*/);Reference: https://react.dev/learn/passing-data-deeply-with-context#use-cases-for-context
Letβs create a Theming Context that toggles our app theme from dark to light mode.
ThemeContext.jsimport { useState, useContext, createContext } from 'react';
const ThemeContext = createContext();
export function useTheme(){
return useContext(ThemeContext);
}
export function ThemeProvider({children}){
const [ theme, setTheme ] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'))
}
return (
<ThemeContext.Provider value={theme, toggleTheme}>
{children}
</ThemeContext.Provider>
)
}πWhat is happening in the code above?ThemeContext- we created contextuseTheme- custom hooks that access theme and toggleTheme function.ThemeProvider- component that will wrap in our application that will provide the theme state and the toggleTheme function
import { ThemeProvider } from './ThemeContext.js';
const App = () => {
return (
<ThemeProvider>
<MainContent />
</ThemeProvider>
)
}import { useTheme } from './ThemeContext';
const MainContent = () => {
const { theme, toggleTheme } = useTheme();
return(
<div className={`${theme}`}> /* lets imagine we have styling class for light and dark mode available :P */
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
)
}πCode Sample: https://codesandbox.io/s/react-context-api-5pjh9p