Gatsby.js Global State w/ React Context & useReducer

Gatsby.js Global State w/ React Context & useReducer

In this video, we'll explore Global State and how to make it persist between pages when working with a Gatsby.js website. We'll first create our global state using React's useReducer hook and Context API. I'll then show you how to incorporate our global state with Gatsby and their wrapRootElement functions.

TLDR: In order to get state to persist between pages with Gatsby, you'll need to add wrapRootElement to both gatsby-ssr.js and gatsby-browser.js. Do not try to wrap it around any <Layout> components.

*Edit: The part about gatsby-ssr.js in the video, I left out the .default when requiring GlobalContextProvider, it should look like this:

// gatsby-ssr.js
const React = require('react');
// highlight-start
const GlobalContextProvider = require('./src/context/GlobalContextProvider').default;
// highlight-end

exports.wrapRootElement = ({ element }) => {
  return <GlobalContextProvider>{element}</GlobalContextProvider>;
};

If you like the YouTube content, please support it by subscribing to the channel!

GitHub Repo: github.com/codebushi/gatsby-global-state