// Tutorial //

State Management in Gatsby using the wrapRootElement Hook

Published on January 3, 2020
Default avatar
By Joshua Hall
Developer and author at DigitalOcean.
State Management in Gatsby using the wrapRootElement Hook

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
2 Comments

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Excellent tutorial! One question: you wrap the returned part of Layout.js with <myContext.Consumer>, and also wrap this around the returned parts of index.js and page-2.js, which are also wrapped with <Layout>. Wouldn’t this mean that the context consumer is loaded twice for those 2 pages? Or is that just not a problem?

Great Writeup!