React's Context API

Passing props to deeply nested components in react has been challenging, especially if the app is small and it does not justify having dedicated state management (redux). But as of react 16.3, there is a Context API that helps pass props to children without “props drilling”. First we need a context const MyContext = React.createContext() and create a provider component where state is going to live:

class MyProvider extends React.Component {
  state = {
    name: 'Dario'
  }
  render() {
    return (
      <MyContext.Provider value={this.state.name}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

Now we can wrap our app or parent component inside MyProvider cpomponent and evety child, regardless how deeply nested, could access value that was passed in MyProvider component.

class App extends React.Component {
  render() {
    return (
      <MyProvider>
        <div>
          <Header />
          <Menu />
        </div>
      </MyProvider>
    );
  }
}

Now we crate consumer - component which will use date from provider.

class Header extends React.Component {
  render() {
    return (
      <div>
        <MyContext.Consumer>
          {(context) => (
            <p>Name: {context.state.name}</p>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}