DEV Community

Dan N
Dan N

Posted on

Next.js: getStaticProps, getServerSideProps, useEffect???

I'm creating a Next.js web app where users can create private logs and attach tags to them. These logs are displayed initally on the main page, and when a new one is added, the page updates automatically. I ran into the question; how do I fetch all of the existing data from the database and display them to the user with Next.js?

Next offered a couple of function options (getStaticProps, getServerSideProps) and I finally landed on a regular React one (useEffect) after some trial and error.

I started with getStaticProps first just to make sure my fetching funcationality was working.

getStaticProps from next docs:

  • The data required to render the page is available at build time ahead of a user’s request
  • The data comes from a headless CMS
  • The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance
  • The data can be publicly cached.

I realized that the data I was working with isn't something that I'd like publicly cached. The logs I'm working with aren't like tweets or blog posts, but rather private to whoever's posting them.

So, I looked to getServerSideProps next.
getServerSideProps from next docs:

You should use getServerSideProps if you need to render a page that relies on personalized user data, or information that can only be known at request time. For example, authorization headers or a geolocation.

It seemed to fit the use case. It runs on the server, and when a user visits a page, getServerSideProps will be used to fetch data at request time. The data is used to render the initial HTML of the page.

It's also fast! This seemed to fit my use case. However, I realized I’d need to be able to run whatever logic I put in there again to update the logs page if someone made a new log. getServerSideProps will do a ONE TIME fetch on the server before rendering your page. It will no longer do anything until a full page refresh.

I finally found what fit my use case, useEffect!
useEffect:

useEffect is a React Hook that lets you synchronize a component with an external system

It's a lifecycle method that activates whenever your component rerenders, based on the criteria you pass it.
Think of an app that refetches new data based on a user clicking a button; useEffect can wait for that click then do a new fetch.

Yes, it's slower than getServerSideProps, but I could get it to run again if a user submits a new log to display the new entry!

Top comments (0)