This article was originally published at codebushi.com
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
Top comments (14)
Great Job, it helped me!, but have one more question, since i'm kinda new with React and global states, what about if i would like to add some state from Component X to this global one? on this tutorial we have hardcoded values that we switch between
actually wans't that hard i found solution :) changed hardcoded ternary operator to dynamic state with initial [], then i push to the array what ever i wanted to, and now i store all my neccessary stuff in array, also you can do that with object, and deeper deeper stuff, or do seperate cases like in redux, for every single thing you want to do, instead o keeping one huge object with all states inside.
The question is, is the performance good? because i guess that every single component change/route in the project will rerender this state, in redux it's rerendered when it's used
wrapping a root element in Gatsby is something i am searching from a long time ! thank you
A great walk through, thank you
Thanks!
Exactly what I needed good job Chang
Thank you!
Simple and easy to use, thank you!
Great one!
Well explained, this really helped me!
Thanks! Glad you enjoyed it.
Hmm...this isn't working for me for some reason. I've setup gatsby-browser and gatsby-ssr but my state does not persist. Has anything changed recently I should be aware of?
I figured this out. Manually changing the URL or using href was the problem. I needed to navigate using Link to or navigate helper function so the state is persisted.
Hunter, great video! This is exactly what I needed. I've been struggling for some time with global context within a Gatsby environment and you made it so easy and clear. Thank you!