React-Hooks Cheatsheet

useContext

useContext

useContext 👜

Notes:

  • useContext saves you the stress of having to rely on a Context consumer.
  • Call signature: const contextValue = useContext(contextObject)
  • It has a simpler API when compared to MyContext.Consumer and the render props API it exposes.
  • View the docs.

// consuming context via a consumer:
const ThemeContext = React.createContext("dark");
function Button() {
return <ThemeContext.Consumer>
{theme => <button className={theme}>Amazing button</button>}
</ThemeContext.Consumer>
}

Here's a live example with ThemeContext.Consumer:

// consume context with the useContext hook:
import {useContext} from 'react';
function ButtonHooks() {
const theme = useContext(ThemeContext)
return <button className={theme}>Amazing button</button>
}

Here's a live example with useContext:

Edit this page on GitHub

On this page