-->

Next.js: Reduce data fetching and share data betwe

2020-07-16 04:44发布

问题:

I'm looking for solutions for better data fetching in a Next.js app. In this question I'm not just looking for a solution, I'm looking for multiple options so we can look at the pros and cons.

The problem I have

Right now I have a few pages that all include a component that displays som static content and a that have some dynamic content that is fetched from an API. Each page do a fetch() in their getInitialProps() to get their own page data, but also the footer data, which is the same for all pages.

This of course works, but there is a lot of duplicated data fetching. The footer data will always be displayed for all pages and always be the same. It will also rarely be changed in the API, so no need for revalidate the data.

The answers I'm looking for

I'm not just looking to solve this one problem, I'm looking for an overview to learn some new practice for future projects as well. I like writing "obvious" code, so not looking for too hacky solutions, like writing to the window object etc. Simple solutions with less dependancies are preferred. The goal is a fast site. It's not that important to reduce network usage/API calls.

What I have thought so far

This is the possible solutions I've come up with, somewhat sorted from simple/obvious to more complex.

  1. Do a fetch inside the Footer component (client side)
  2. Do a fetch in getInitialProps (server side & client side) on all /pages
  3. Do a fetch in _app.js with a HOC and hooking into it's getInitialProps() and add it to props, so data is available for all pages
  4. Use zeit/swr and data prefetching to cache data
  5. Use redux to store a global state

All of these "work", but most of them will refetch the data unnecessarily, and/or adds a bit more complexity. Here are the pros/cons as I see it (numbers are the same as above):