30 Gatsby Best Practices in 2023 and Beyond
January 31, 2023 • 8 min read
As a modern, blazing fast static site generator, Gatsby offers a plethora of tools and features for building high-performance websites and applications. Here are 30 best practices to keep in mind when using Gatsby in 2023 and beyond:
1. Use Gatsby plugins:
To add functionality to your site, utilize the vast array of Gatsby plugins available in the Gatsby Plugin Library. For example:
module.exports = {
plugins: [`gatsby-plugin-sass`, `gatsby-transformer-json`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`],
}
2. Optimize images:
Use the gatsby-image plugin to optimize images for better performance and provide a smoother user experience.
import Img from 'gatsby-image'
const Image = () => <Img fluid={data.image.childImageSharp.fluid} alt='Description of image' />
3. Use GraphQL:
Utilize Gatsby's built-in GraphQL data layer to efficiently fetch and manage data for your site.
query {
site {
siteMetadata {
title
description
}
}
}
4. Minimize the number of requests:
Minimize the number of requests made to the server by lazy loading images and using CSS and JavaScript code splitting.
import loadable from '@loadable/component'
const OtherComponent = loadable(() => import('./OtherComponent'))
5. Use a CSS-in-JS solution:
Use a CSS-in-JS solution, such as styled-components, to write modular and maintainable CSS code.
import styled from "styled-components"
const Container = styled.div`max-width: 1000px;
margin: 0 auto;
padding: 20px;`
6. Implement PWA features:
Use the gatsby-plugin-offline plugin to implement progressive web app (PWA) features, such as offline support and background sync.
7. Use environment variables:
Use environment variables to separate configuration from code and make it easier to manage different environments.
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
})
console.log(process.env.API_KEY)
8.Make use of source plugins:
Make use of Gatsby's source plugins, such as gatsby-source-filesystem, to fetch data from a variety of sources, including local files, APIs, and databases.
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
],
}
9. Use gatsby-link:
Use gatsby-link instead of regular link components, such as a, to ensure seamless navigation within your Gatsby site.
import { Link } from 'gatsby'
const Navigation = () => (
<nav>
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about/'>About</Link>
</li>
<li>
<Link to='/contact/'>Contact</Link>
</li>
</ul>
</nav>
)
10. Implement SEO:
Use plugins like gatsby-plugin-react-helmet to manage the head elements of your pages and improve SEO.
import { Helmet } from 'react-helmet'
const SEO = ({ title, description }) => (
<Helmet>
<title>{title}</title>
<meta name='description' content={description} />
</Helmet>
)
11. Use TypeScript:
Consider using TypeScript, a statically-typed language, to improve the quality and maintainability of your code.
import React from "react"
interface Props {
title: string
description: string
}
const Component: React.FC<Props> = ({ title, description }) => (
<>
<h1>{title}</h1>
<p>{description}</p>
</>
)
12. Implement testing:
Implement testing using tools like Jest and React Testing Library to ensure the quality and stability of your code.
import React from 'react'
import { render } from '@testing-library/react'
import Component from './Component'
describe('Component', () => {
it('renders the title and description', () => {
const { getByText } = render(<Component title='Title' description='Description' />)
expect(getByText('Title')).toBeInTheDocument()
expect(getByText('Description')).toBeInTheDocument()
})
})
13. Use the Gatsby CLI:
Use the Gatsby CLI to quickly and easily generate new components, pages, and plugins.
gatsby new my-site
gatsby generate component my-component
gatsby generate page my-page
14. Minimize the size of your code:
Minimize the size of your code by using tools like Babel and UglifyJS to transpile and minify your code.
module.exports = {
plugins: [`gatsby-transformer-babel-minify`],
}
15. Make use of Gatsby's APIs:
Make use of Gatsby's APIs, such as the StaticQuery and useStaticQuery hooks, to fetch data and manage state in your components.
import { useStaticQuery, graphql } from 'gatsby'
const Component = () => {
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
description
}
}
}
`)
return (
<>
<h1>{data.site.siteMetadata.title}</h1>
<p>{data.site.siteMetadata.description}</p>
</>
)
}
16. Use source plugins to fetch data:
Use source plugins to fetch data from APIs and databases, such as the gatsby-source-contentful plugin.
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `<space_id>`,
accessToken: `<access_token>`,
},
},
],
}
17. Implement responsive design:
Use CSS media queries and responsive design techniques to ensure your website looks great on all devices.
@media (min-width: 768px) {
.container {
max-width: 768px;
margin: 0 auto;
}
}
18. Make use of Gatsby's image optimization:
Make use of Gatsby's image optimization capabilities to optimize images for performance and improve load times.
import { useStaticQuery, graphql } from 'gatsby'
import Img from 'gatsby-image'
const Image = () => {
const data = useStaticQuery(graphql`
query {
placeholderImage: file(relativePath: { eq: "image.jpg" }) {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return <Img fluid={data.placeholderImage.childImageSharp.fluid} />
}
19. Use CSS-in-JS libraries:
Consider using CSS-in-JS libraries, such as Emotion, to write and manage your CSS.
import React from 'react'
import styled from '@emotion/styled'
const Container = styled.div`
max-width: 800px;
margin: 0 auto;
padding: 32px;
`
const Component = () => (
<Container>
<p>Content goes here</p>
</Container>
)
20. Minimize the number of dependencies:
Minimize the number of dependencies you use to improve performance and reduce the risk of security vulnerabilities.
{
"dependencies": {
"gatsby": "^2.24.83",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"gatsby-cli": "^2.12.79"
}
}
21. Make use of code splitting:
Make use of code splitting to improve performance by only loading the code that's needed for a specific page.
import React, { lazy, Suspense } from 'react'
const LazyComponent = lazy(() => import('./LazyComponent'))
const Component = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
)
22. Use the right data structure:
Choose the right data structure to store your data, such as JSON or YAML, and make use of the right tools to manipulate that data, such as GraphQL or plain JavaScript.
export const query = graphql`
query MyQuery {
site {
siteMetadata {
title
description
}
}
}
`
const Component = ({ data }) => (
<>
<h1>{data.site.siteMetadata.title}</h1>
<p>{data.site.siteMetadata.description}</p>
</>
)
23. Use environment variables:
Use environment variables to store sensitive information, such as API keys, and make sure to keep them secure.
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
],
}
24. Make use of Gatsby's caching capabilities:
Make use of Gatsby's caching capabilities to improve performance by caching data and pages.
import { useStaticQuery, graphql } from 'gatsby'
const Component = () => {
const data = useStaticQuery(graphql`
query MyQuery {
site {
siteMetadata {
title
description
}
}
}
`)
return (
<>
<h1>{data.site.siteMetadata.title}</h1>
<p>{data.site.siteMetadata.description}</p>
</>
)
}
25. Make use of prefetching and preloading:
Make use of prefetching and preloading to improve performance by loading assets ahead of time.
import React, { lazy, Suspense } from 'react'
const LazyComponent = lazy(() => import('./LazyComponent'))
const Component = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
)
26. Make use of source maps:
Make use of source maps to help debug your code and see where errors are happening in the original source code.
// gatsby-config.js
module.exports = {
plugins: [`gatsby-plugin-source-map-support`],
}
27. Keep your dependencies up-to-date: Keep your dependencies up-to-date to ensure that you're using the latest versions and to reduce the risk of security vulnerabilities.
{
"dependencies": {
"gatsby": "^2.24.83",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"gatsby-cli": "^2.12.79"
}
}
28. Make use of progressive web features:
Make use of progressive web features, such as service workers and web manifest, to make your website work offline and be installable as a native app.
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `My App`,
short_name: `MyApp`,
start_url: `/`,
background_color: `#f7f0eb`,
theme_color: `#a2466c`,
display: `standalone`,
icon: `src/images/icon.png`,
},
},
`gatsby-plugin-offline`,
],
}
29. Make use of code splitting:
Make use of code splitting to only load the code that's needed for each page, improving performance and reducing the size of the JavaScript file.
import React, { lazy, Suspense } from 'react'
const LazyComponent = lazy(() => import('./LazyComponent'))
const Component = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
)
30. Make use of Lighthouse:
Make use of Lighthouse to check the performance, accessibility, and SEO of your website and make improvements accordingly.
npm install -g lighthouse
lighthouse https://www.example.com
In conclusion, following these 30 best practices in 2023 and beyond will help you build high-performing, secure, and maintainable Gatsby websites. By taking advantage of the power of Gatsby CLI, GraphQL, plugins, React components, CSS-in-JS, TypeScript, themes, and source plugins, you can create dynamic and engaging websites that meet the needs of your audience. Whether you’re building a static site, e-commerce site, or blog, these best practices will help you create the best Gatsby website possible.
Category - Browse all categories
About Baby Panda Codes
Full-Stack Engineer
Baby Panda Codes is an experienced Full-Stack Engineer and trainer, focusing on code quality.