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');
const GlobalContextProvider = require('./src/context/GlobalContextProvider').default;
exports.wrapRootElement = ({ element }) => {
  return <GlobalContextProvider>{element}</GlobalContextProvider>;
};

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

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

Learn JavaScript and React

Here are some of my favorite courses for learning JavaScript and React. I have personally purchased each of these and found them extremely helpful when I was learning JavaScript and React. Check out the resources page for more.