An online markdown blog and knowledge repository.
Props:
Context:
When passing props to deeply nested components, props can become more difficult to manage, passing props through many children to the place the data needs to go in the hierarchy.
Context API allows specifying pieces of data available to all components without having to pass data through each component.
React.createContext:
In React Class Components, Context components must wrap the child components and the function variable must be passed-in (and out) of the Context Provider and Consumer, respectively.
In React Function Components, useContext
hook allows bypassing the Component wrapping, which simplifies code.
Pass your custom Context to 'useContext' hook:
const { theme, setTheme } = useContext(ThemeContext);
<p>{theme}</p>
and ...onClick={()=>setTheme('light')}...
This bypasses having to wrap Components in Consumer and Provider elements.
useContext
as an interface for consuming context.Examples were borrowed from videos and the WDS Blog.