Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Pages and Routing

Layouts and Shared Components

Share headers, footers and structure across Gatsby pages with layout components, wrapPageElement, wrapRootElement, children props and Gatsby 5 slices explained.

Almost every site repeats the same frame around its content: a header, a navigation bar, a footer. You would not copy that markup into every page. Gatsby gives you several ways to share it, from a simple layout component to wrappers that apply automatically to every page, to the newer Slice API that lets shared parts update without rebuilding every page.

All Gatsby code below is read-only; stand-ins run the same composition ideas as plain JavaScript functions.

A layout is a component with children

The simplest approach is a normal React component that accepts children:

JSX
// src/components/layout.js (real Gatsby, read-only)
import * as React from "react"
import { Link, useStaticQuery, graphql } from "gatsby"

const Layout = ({ pageTitle, children }) => {
  const data = useStaticQuery(graphql`
    query { site { siteMetadata { title } } }
  `)

  return (
    <div className="wrapper">
      <header>
        <Link to="/">{data.site.siteMetadata.title}</Link>
        <nav>
          <Link to="/about/">About</Link>
          <Link to="/blog/">Blog</Link>
        </nav>
      </header>
      <main>
        <h1>{pageTitle}</h1>
        {children}
      </main>
      <footer>Copyright {new Date().getFullYear()}</footer>
    </div>
  )
}

export default Layout

Each page imports and uses it:

JSX
// src/pages/about.js
import Layout from "../components/layout"

const AboutPage = () => (
  <Layout pageTitle="About us">
    <p>We write about coffee.</p>
  </Layout>
)
export default AboutPage

This is explicit and easy to understand: you can see the layout in each page and give different pages different layouts or props. The drawback: the layout is unmounted and remounted on every navigation because it lives inside the page component. State inside it (an open menu, a scroll position) resets.

useStaticQuery is explained in page queries and useStaticQuery.

wrapPageElement: one layout for every page

To apply a layout automatically, wrap pages in both gatsby-browser.js and gatsby-ssr.js. The two files must do the same thing, or the server HTML and the browser will differ and React will complain:

JSX
// gatsby-browser.js and gatsby-ssr.js (real Gatsby, read-only)
import * as React from "react"
import Layout from "./src/components/layout"

export const wrapPageElement = ({ element, props }) => {
  return <Layout {...props}>{element}</Layout>
}

Gatsby keeps this wrapper mounted between page changes. State survives navigation, which is useful for persistent menus, audio players or animations that must not restart. Choose the layout per page by reading props.pageContext or props.location.

wrapRootElement: providers for the whole app

For things that wrap everything, such as a theme provider, a Redux store or a React context, use wrapRootElement:

JSX
// gatsby-browser.js and gatsby-ssr.js (real Gatsby, read-only)
import * as React from "react"
import { ThemeProvider } from "./src/context/theme"

export const wrapRootElement = ({ element }) => (
  <ThemeProvider>{element}</ThemeProvider>
)

Rule of thumb: wrapRootElement for providers, wrapPageElement for visual layout.

flowchart TD
  R["wrapRootElement<br/>providers, mounted once"] --> P["wrapPageElement<br/>layout, persists across pages"]
  P --> C["Page component<br/>changes on navigation"]

The outer wrappers stay alive; only the page component changes.

The Slice API (Gatsby 5)

A component used on thousands of pages, like a header, normally means rebuilding every page when the header changes. Slices solve this: you declare the header as a named slice, the build creates it once, and each page only references it. Change the header and only the slice is rebuilt.

JavaScript
// gatsby-node.js (real Gatsby, read-only)
exports.createPages = async ({ actions }) => {
  actions.createSlice({
    id: "header",
    component: require.resolve("./src/components/header.js"),
  })
}
JSX
// in the layout
import { Slice } from "gatsby"

<Slice alias="header" />

Slices cannot receive arbitrary function props, and they need a build platform that supports them for the full benefit. For small and medium sites, a layout component is enough.

Stand-in: composing a layout around pages

This stand-in is not Gatsby. Components are functions that return strings, and wrapPage plays the role of wrapPageElement.

JS Stand-in: wrapPageElement as function composition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: why mounting matters

Remember the difference between a layout inside the page and a wrapper that persists. This stand-in counts how often a menu component is created in each approach.

JS Stand-in: remounting versus persisting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If wrapPageElement is present in gatsby-browser.js but missing in gatsby-ssr.js (or different), the static HTML and the first client render disagree and you get hydration errors or flashes of unstyled content. Share one function and import it in both files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a layout component receive to render page content?

    Pages place their content inside the layout, which renders it with children.
  2. 2. Which API keeps a layout mounted across navigation?

    wrapPageElement wraps every page in one persistent wrapper.
  3. 3. Where must wrapPageElement be implemented?

    Both files must match so the server HTML and the browser agree.
  4. 4. What problem do slices solve?

    A slice is built once and referenced by pages, so only the slice rebuilds when it changes.

Summary

  • A layout component with children is the simplest and most explicit way to share structure.
  • wrapPageElement applies a layout to all pages and keeps it mounted; wrapRootElement is for providers.
  • Implement the wrappers identically in gatsby-browser.js and gatsby-ssr.js.
  • Gatsby 5 slices make heavily shared parts cheap to update.
  • Pick by need: explicit layout for most sites, wrapper for persistent state.

Next: Styling in Gatsby