Reference useContext

  • useContext: is wrapper to help stop prop drilling.
  • useContext: is made of 2 parts, provide and context hook.
  • On the provider you get access to one props called 'value'.
  • I have put 2 examples in this, one with custom hook one without.
  • It is common to use with custom hooks when using useContext.
Example - Coral
Example with customhook- Dark
WDS Video on this Hook
import React, { useContext } from "react"; function ExampleUseContext() { const [basicTheme, setBasicTheme] = useContext(BasicThemeContext); function exampleContext() { setBasicTheme((preTheme) => !preTheme); } return ( <Stack alignItems={"center"} sx={{ backgroundColor: basicTheme ? "coral" : "lightblue", }} > <Typography variant="h6" sx={{ marginBottom: 5 }}> Example - {basicTheme ? "Coral" : "Blue"} </Typography> <Stack direction={"row"} alignItems={"center"} gap={5}> <Button variant="contained" onClick={() => exampleContext()}> Change </Button> </Stack> </Stack> ) } // App Component export const BasicThemeContext = React.createContext(); function App() { const [basicTheme, setBasicTheme] = useState(true); return ( <BasicThemeContext.Provider value={[basicTheme, setBasicTheme]}> <MainApplication /> </BasicThemeContext.Provider> );