Use
getStaticProps
as react hooks
Writing one large query per page doesn't organize well. Asynchronous data fetching frameworks like apollo, relay, and react-query already allow you to write the queries closer to the component.
Why can't static data queries be written closer to the component too?
next-data-hooks
is a small and simple lib that lets you write React hooks for static data queries in Next.js by lifting static props into React Context.
See the example in this repo for some ideas on how to organize your static data calls using this hook.
- Install
npm i next-data-hooks
or
yarn add next-data-hooks
- Add Provider to
_app.tsx
or_app.js
import { AppProps } from 'next/app';
import { NextDataHooksProvider } from 'next-data-hooks';
function App({ Component, pageProps }: AppProps) {
const { children, ...rest } = pageProps;
return (
<NextDataHooksProvider {...rest}>
<Component {...rest}>{children}</Component>
</NextDataHooksProvider>
);
}
- Add the babel plugin
At the root, add a .babelrc
file that contains the following:
{
"presets": ["next/babel"],
"plugins": ["next-data-hooks/babel"]
}
β οΈ Don't forget this step. This enables code elimination to eliminate server-side code in client code.
- Create a data hook. This can be in the same file as the component you're using it in or anywhere else.
import { createDataHook } from 'next-data-hooks';
// this context is the GetStaticPropsContext from 'next'
// π
const useBlogPost = createDataHook('BlogPost', async (context) => {
const slug = context.params?.slug as string;
// do something async to grab the data your component needs
const blogPost = /* ... */;
return blogPost;
});
export default useBlogPost;
- Use the data hook in a component. Add it to a static prop in an array with other data hooks to compose them downward.
import ComponentThatUsesDataHooks from '..';
import useBlogPost from '..';
import useOtherDataHook from '..';
function BlogPostComponent() {
const { title, content } = useBlogPost();
const { other, data } = useOtherDataHook();
return (
<article>
<h1>{title}</h1>
<p>{content}</p>
<p>
{other} {data}
</p>
</article>
);
}
// compose together other data hooks
BlogPostComponent.dataHooks = [
...ComponentThatUsesDataHooks.dataHooks,
useOtherDataHooks,
useBlogPost,
];
export default BlogPostComponent;
- Pass the data hooks down in
getStaticProps
.
import { getDataHooksProps } from 'next-data-hooks';
import { GetStaticPaths, GetStaticProps } from 'next';
import BlogPostComponent from '..';
export const getStaticPaths: GetStaticPaths = async (context) => {
// return static paths...
};
export const getStaticProps: GetStaticProps = async (context) => {
const dataHooksProps = await getDataHooksProps({
context,
// this is an array of all data hooks from the `dataHooks` static prop.
// πππ
dataHooks: BlogPostComponent.dataHooks,
});
return {
props: {
// spread the props required by next-data-hooks
...dataHooksProps,
// add additional props to Next.js here
},
};
};
export default BlogPostComponent;
Next.js has a very opinionated file-based routing mechanism that doesn't allow you to put a file in the /pages
folder without it being considered a page.
Simply put, this doesn't allow for much organization.
With next-data-hooks
, you can treat the /pages
folder as a folder of entry points and organize files elsewhere.
my-project
# think of the pages folder as entry points to your routes
βββ pages
β βββ blog
β β βββ [slug].ts
β β βββ index.ts
β βββ shop
β βββ category
β β βββ [slug].ts
β βββ index.ts
β βββ product
β βββ [slug].ts
|
# think of each route folder as its own app with it's own components and helpers
βββ routes
βββ blog
β βββ components
β β βββ blog-index.tsx
β β βββ blog-post-card.tsx
β β βββ blog-post.tsx
β βββ helpers
β βββ example-blog-helper.ts
βββ shop
βββ components
β βββ category.tsx
β βββ product-description.tsx
β βββ product.tsx
βββ helpers
βββ example-shop-helper.ts
import { createDataHook } from 'next-data-hooks';
// write your data hook in a co-located place
const useBlogPostData = createDataHook('BlogPost', async (context) => {
const blogPostData = // get blog post dataβ¦
return blogPostData;
});
function BlogPost() {
// use it in the component
const { title, content } = useBlogPostData();
return (
<article>
<h1>{title}</h1>
<p>{content}</p>
</article>
);
}
BlogPost.dataHooks = [useBlogPostData]
export default BlogPost;
import { GetStaticProps, GetStaticPaths } from 'next';
import { getDataHooksProps } from 'next-data-hooks';
import BlogPost from 'routes/blog/components/blog-post';
export const getStaticPaths: GetStaticPaths = {}; /* ... */
export const getStaticProps: GetStaticProps = async (context) => {
const dataHooksProps = getDataHooksProps({
context,
dataHooks: BlogPost.dataHooks,
});
return { props: dataHooksProps };
};
// re-export your component. this file is just an entry point
export default BlogPost;
π Note: the above is just an example of how you can use
next-data-hooks
to organize your project. The main takeaway is that you can re-export page components to change the structure andnext-data-hooks
works well with this pattern.
For smaller bundles, Next.js eliminates code that is only intended to run inside getStaticProps
.
next-data-hooks
does the same by a babel plugin that prefixes your data hook definition with typeof window !== 'undefined' ? <stub> : <real data hook>
.
This works because Next.js pre-evaluates the expression typeof window
to 'object'
in browsers. This will make the above ternary always evaluate to the <stub>
in the browser. Terser then shakes away the <real data hook>
expression eliminating it from the browser bundle.
If you saw the error Create data hook was run in the browser.
then something may have went wrong with the code elimination. Please open an issue.
π Note. There may be differences in Next.js's default code elimination and
next-data-hooks
code elimination. Double check your bundle.