JACOB SILVER

web developer | musician | venue booker

React Context API

React’s new Context API is great way to access properties from nested components without having to send down props from one component to another, and another, and another… It works a bit like Redux. I’m thinking it’s best to use for apps that might not need all the power of Redux, but still need some basic central “store”. It works like this:

First of all make a new React project with create-react-app. Then once you’ve cd’ed into your new react app, make sure you’re using the latest version of React. Do that by typing into your terminal npm install react@next react-dom@next.

In order to use Context, you’ll need to make a new React component to hold the “store”. So first, we’ll make our app component.

class App extends Component {

    render() {

    return(
        <div>
        <p>Hello</p>
        </div>
    )}}

And then we will create the store, or the “provider”. We will store our state in here.

//make sure to make a new context from React
const TheContext = React.createContext();

class TheProvider extends Component {
    state = {
        user: 'Jacob',
        posts: 0,
    }

    //you need to return a context provider

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

And then after that, you need to wrap your App component in the new provider component. Don’t forget to import it!

class App extends Component {

    render() {

    return(
        <TheProvider>
            <div>
                <p>Hello</p>
            </div>
        </TheProvider>
    )}}

After that, any child will be able to access the data within the provider! So, if we made another component called, User, and rendered it from our App component, like so:

class User extends Component {
    render() {
    return(
        <div className="user">
            <TheContext.Consumer>
                {(context) => (
                //note that you need to use React.Fragment when rendering multiple pieces of state!
                <React.Fragment>
                    <p> User: {context.state.user}</p>
                    <p> Posts: {context.state.posts}</p>
                </React.Fragment>                
                )}
            </TheContext.Consumer>
        </div>
    )}}

class App extends Component {

    render() {

    return(
        <TheProvider>
            <div>
                <p>Hello</p>
                <User />
            </div>
        </TheProvider>
    )}}

Pretty cool! In another post I’ll demonstrate how to update/remove, or anything really via the Context Api. Hint: It works a lot like dispatch/reducers/actions.