useContext
Accepts a context object (the value returned from React.createContext) and returns the current context value for that context.
The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.
When the nearest <MyContext.Provider> above the component updates, this Hook will trigger a re-render with the latest context value passed to that MyContext provider.
Context.Provider allows for a variable or prop to be passed into the value prop, enabling it to be used by all children without needing to pass it to them manually.
A component calling useContext will always re-render when the context value changes.
This is used in styled components! Look here for examples.
The class-based version and the function-based version have different syntax.
The class-based version doesn't use useContext, and thus is more complex code (and more lines of code).
The function-based version does use useContext, and is much cleaner code.
Example
Class-based theme
export default class ClassContext extends Component
themeStyles(dark) { return { backgroundColor: dark ? '#333' : '#CCC', color: dark ? '#ccc' : '#333', padding: '8px', width: '400px', margin: '8px auto', }; }
<ThemeContext.Consumer> {(darkTheme) => { return ( <div style={this.themeStyles(darkTheme)}> <p>Class-based theme</p> </div> ); }} </ThemeContext.Consumer>
Function-based theme
const darkTheme = useContext(ThemeContext);
const themeStyles = { backgroundColor: darkTheme ? '#333' : '#CCC', color: darkTheme ? '#ccc' : '#333', padding: '8px', width: '200px', height: '100px', margin: '8px auto', };