wrapPageElement vs wrapRootElement - Detail Guide - When to Use?
Sometimes it might be confusing which one to use among wrapPageElement
and wrapRootElement
. In this I will explain you when to use which by keeping it simple.
Use wrapPageElement - Advantages
- [x] For wrapper elements like Header and Footer - They won't get unmounted when you navigate between pages
const React = require("react")
const Layout = require("./src/components/layout").default
exports.wrapPageElement = ({ element, props }) => {
// props provide same data to Layout as Page element will get
// including location, data, etc - you don't need to pass it
return <Layout {...props}>{element}</Layout>
}
Use wrapRootElement - Advantages
- [x] For Provider components like redux - At the end, every component is wrapped by wrapRootElement, even the wrapPageElement
Instantiating store in wrapRootElement
handler ensures:
- there is fresh store for each SSR page
- it will be called only once in browser, when React mounts
import React from "react";
import { Provider } from "react-redux";
import createStore from "./src/state/createStore";
export const wrapRootElement = ({ element }) => {
const store = createStore();
return <Provider store={store}>{element}</Provider>;
};;
It is recommended to use Gatsby’s SSR and Gatsby’s Browser APIs together when you are using wrapRootElement
and wrapPageElement
Last Updated on
Comments