React Context API

The Context API is a clever way to pass state between applications without the use of props

ThisContext APIThis feature was introduced to allow you to pass state (and allow state updates) in the app without using props.

If you have only a few levels of kids to pass, the React team recommends sticking to props, as it is still much more complicated than the Context API.

In many cases, it prevents us from usingRedux, Greatly simplified our application, and also learned how to use React.

How does it work?

You use the creation contextReact.createContext(), It returns a Context object.

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

Then you create a wrapper component that returns aproviderComponent, and then add all components from which you want to access the context as child components:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      something: 'hey'
    }
  }

render() { return ( <Provider value={{ state: this.state }}>{this.props.children}</Provider> ) } }

class HelloWorld extends React.Component { render() { return ( <Container> <Button /> </Container> ) } }

I use Container as the name of the component because this will be a global provider. You can also create smaller contexts.

Inside the component wrapped in the provider, you can useconsumerComponents that utilize context:

class Button extends React.Component {
  render() {
    return (
      <Consumer>
        {context => <button>{context.state.something}</button>}
      </Consumer>
    )
  }
}

You can also pass functions into the Provider value, and users will use these functions to update the context state:

<Provider value={{
  state: this.state,
  updateSomething: () => this.setState({something: 'ho!'})}}>
  {this.props.children}
</Provider>

/* … */ <Consumer> {(context) => ( <button onClick={context.updateSomething}>{context.state.something}</button> )} </Consumer>

You can see this actionIn this glitch.

You can create multiple contexts so that your state is distributed among the various components, but you can expose it and make it accessible to any required component.

When using multiple files, you can create content in one file and then import it to all usage locations:

//context.js
import React from 'react'
export default React.createContext()

//component1.js import Context from ‘./context’ //… use Context.Provider //component2.js import Context from ‘./context’ //… use Context.Consumer

Download mine for freeResponse Handbook


More response tutorials: