REACT:

the Context API

by Gian Marco Toso   -   @gianmarcotoso

self employed / polarityb.it

starting at 11:30

The Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

- Official React Docs

How Does it work?

React.createContext(defaultValue)

returns both a Provider and a Consumer

const { Provider, Consumer } = React.createContext('light')

Wrapping a component tree with a Provider makes it so that every time its value changes, all the contained Consumers automatically re-render.

return (
    <Provider value={this.state.theme}>
        <MyApp />
    </Provider>
)
const MyApp = () => (
    <Consumer>
        {theme => (
            <Application useTheme={theme} />
        )}
    <Consumer>
)

When Should I use it?

  • Sharing simple data between components (The current theme, etc...)
  • Application-wide functionality (Notification Managers, etc...)

Open discussion

  • Can I use multiple contexts?
  • When should I *not* use context?
Made with Slides.com