State Management in Gatsby using the wrapRootElement Hook

Joshua Hall

Since Gatsby handles our routes for us, that leaves us with nowhere to wrap our app with a Redux store or provider. In this article we’ll learn a clever trick to get around that.

For the sake of simplicity, all of the examples will be using React’s Context API for our state management to save time from setting up boilerplate, but everything is still applicable to other state management methods. If you need to brush up on working with providers, you can check out this intro to the useContext hook.

Installation

I prefer to start with a very basic theme, but in the end we only need something with two pages so we can see that our state is being applied globally. Since we’ll be working with some styling I’ll add Sass support with node-sass and gatsby-plugin-sass, because I’m not an animal.

$ gatsby new stateful-gatsby https://github.com/gatsbyjs/gatsby-starter-defaultCopyInstall
$ cd stateful-gatsby
$ yarn add node-sass gatsby-plugin-sass -D

Wrapping with Provider

The first step is to setup our context provider with a simple isDark state and a method to reverse its current state. We’ll take whatever is passed-in as props and wrap it in our new myContext.Provider.

provider.js

import React, { useState } from 'react';

export const myContext = React.createContext();

const Provider = props => {
  const [isDark, setTheme] = useState(false);

  return (
    <myContext.Provider value={{
      isDark,
      changeTheme: () => setTheme(!isDark)
    }}>
      {props.children}
    </myContext.Provider>
  )
};

Just below it, we’ll export a function that’ll wrap whatever is passed to it in our new provider.

export default ({ element }) => (
  <Provider>
    {element}
  </Provider>
);

Now that we have a way to manage our state, Gatsby offers us a neat little hook called wrapRootElement, which you can check out in the docs. This hook takes most of our site and passes it as props into a function we give it, like the one we just exported from Provider.js, giving us the perfect little space to wrap everything inside.

Both gatsby-browser.js and gatsby-ssr.js have access to this hook and it’s recommended to wrap both with our provider, that’s why we defined the wrapper function in provider.js.

import Provider from './provider';

export const wrapRootElement = Provider;

Styling

Here are our simple theme styles:

src/global.sass

.colorTheme 
    height: 100vh
    transition: .3s ease-in-out

.darkTheme 
    @extend .colorTheme
    background-color: #1A202C
    color: #fff
    a
        color: yellow

.lightTheme 
    @extend .colorTheme
    background-color: #fff
    color: #000

Applying Themes

The only thing we need to do to access our state is wrap each component in a myContext.Consumer and access our global state on context, React.Fragment is just to let us add more than one element.

For our background color we can set our class conditionally to our state, if you had more than one theme you could set the provider’s theme as a string with our class name.

layout.js

import { myContext } from '../../provider';
import '../global.sass';

 return (
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <div className={context.isDark ? 'darkTheme' : 'lightTheme'}>
            {/* ... */}
          </div>
        </React.Fragment>
      )}
    </myContext.Consumer>
  )

We also have access to setTheme because we passed it to the changeTheme method. Let’s add a button to reverse isDark.

src/pages/index.js

import { myContext } from '../../provider';

const IndexPage = () => (
  <Layout>
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <SEO title="Home" />
          <h1>{context.isDark ? "Dark Theme" : "Light Theme"}</h1>

          <button onClick={() => context.changeTheme()}>{context.isDark ? "Light" : "Dark"}</button>

          <Link to="/page-2/">Go to page 2</Link>
        </React.Fragment>
      )}
    </myContext.Consumer>
  </Layout>
);

Now if you add essentially the same configuration to page-2.js you should be able to change the state and move between them with the state remaining consistent between them.

page-2.js

import { myContext } from '../../provider';

const SecondPage = () => (
  <Layout>
    <myContext.Consumer>
      {context => (
        <React.Fragment>
          <SEO title="Page two" />
          <h1>{context.isDark ? "Dark Theme" : "Light Theme"}</h1>
          <p>Welcome to page 2</p>

          <button onClick={() => context.changeTheme()}>{context.isDark ? "Light" : "Dark"}</button>

          <Link to="/">Go back to the homepage</Link>
        </React.Fragment>
      )}
    </myContext.Consumer>
  </Layout>
);

image description

Huzza! it’s really as simple as that, 3 small file changes and wrapping everything in a consumer and you’re good to go.

Conclusion

For me, this wasn’t a very obvious way of doing things so I hope this was helpful in understanding how to use the wrapRootElement hook to your advantage.

For the sake of convenience I’ve created a repo with this setup as a starter, which you can check out here.

  Tweet It

🕵 Search Results

🔎 Searching...