Discovering the power of SWR: Implementation of getServersideProps or GetStaticProps

Struggling to implement GetServerSideProps with SWR, as the clientside keeps fetching data even though it's already loaded from the server side.

Here is an example scenario:

  1. We retrieve a wordlist from the API based on word length in getServerSide/getStaticProps and SSR/SSG build the page for quick delivery.

  2. User interacts with the page triggering iterateWordLength().

  3. We then fetch an updated wordlist using mutate.

Current issue: SWR fires twice on load

  1. Serverside runs only once ✅
  2. Wordlist useEffect triggers - displays the word "foo" fetched by artificial getServerSideProps ✅
  3. WordClientSideFetcher also triggers ❌ (shouldn't because we already have the data)
  4. Wordlist changed event fires again ❌

I am avoiding useSWRImmutable due to dynamic fetcher and changing GET parameters based on another state variable.

Despite setting revalidate options to false, why does it still fire twice?

Below is a simplified version of Index.js:

function Index( { fallback } ) {

const [wordLength, setWordLength] = useState(DEFAULT_WORD_LENGTH);  

  const { data: wordlist, mutate } = useSWR('/api/wordlist', clientSideFetcher, { 
    fallbackData: fallback['/api/wordlist'],
    revalidateIfStale: false,
    revalidateOnMount: false, 
    revalidateOnFocus: false 
  })
}

  useEffect(()=>{
   // iterates word length
    mutate() // updates wordlist
  }, [wordLength]) 

  useEffect(()=>{
    console.log("### Wordlist changed")
    setWord( generateRandomWord() )
  },[wordlist])

  const iterateWordlength = () => { setWordlength(wordLength+1)}

export async function staticFetcher() {
  const res = await fetch(API_URL)
  const data = await res.json()
  console.log(`### staticFetcher fetched ${data.length} words`)
  return new Wordlist(...data) 
}

export async function getServerSideProps(context) { 
  const staticWordlist = await staticFetcher(context)
    .catch( err => {
      return { notFound: true }
    })
  const props = { 
    fallback: {
      '/api/wordlist' : ["foo"] 
    }
  }
  return { props }
}

Answer №1

The reason for this behavior can be attributed to the implementation of React18 strict mode, which is not intended for production builds.
Essentially, it results in components being mounted twice (mounted, unmounted, then remounted), causing any code within the useEffect hook to execute twice.

While there is an option to disable this feature in nextjs, it is recommended to leave it enabled as-is.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

Please define a unique "redirect_uri" in the FB.ui() function for posting purposes

I'm currently utilizing the "Facebook Javascript Sdk" to publish messages on a user's wall. However, I am facing an issue with dynamic redirect URLs. Even though I am explicitly passing the "redirect_uri" as a link with query string in the FB.ui ...

Is it possible to duplicate native functions in JavaScript, such as window.alert or document.write?

I am looking to replace all instances of the alert function in my code with a custom alert message saying "you used alert". var hardCodedAlert = alert; //Although I understand this won't work. What other approach can I take? window.alert=function(){ ...

Assign the button's id to JavaScript

When working with JavaScript code, I am faced with the task of creating a line similar to the one shown below (I am using the smarty template engine which processes literal content). <script language="javascript" type="text/javascript"> function ...

Transmit information from javascript to the server

I am currently working on an ASP.NET MVC web application and have a query: If I have a strongly typed view and I submit it, the object (of the strongly type) will be filled and sent to the server. But what if one of the properties of the strongly typed i ...

Script to automatically open a PDF document immediately after it has been generated

Can Apps Script in Google Sheets automatically open a PDF file right after it's created? I have a script that generates a PDF from a Google Sheet and saves it on Google Drive. Is there a way for the script to also open the PDF so it can be easily pri ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

Develop numerous tags with diverse characteristics using JavaScript

I am struggling with JavaScript and need help finding a solution. I want to dynamically create 4 HTML tags using JavaScript, each with different innerHTML and href attributes. I attempted to create multiple "newA" variables for each tag, but that approac ...

Firefox is unable to render the jQuery file from ajax.googleapis.com

I have Mozilla Firefox version 20.0.1 installed, and I am using the following code on my website: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!--<script s ...

What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods? async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> { //log getAllActiveRooms return this.i.knex('users_rooms') .transacting(ctx ...

Exploring Namespaces in JavaScript: A Detailed Example and Syntax Breakdown

Example and explanation of JavaScript namespaces tree. The following namespaces need to be defined in JavaScript: root root.person root.home root.home.relative My attempt that was incorrect: var root=''; root.person=''; roo ...

Is jQuery the better choice for Bootstrap form validation as opposed to using plain JavaScript?

While exploring Bootstrap for form validation, I came across this example using plain JavaScript instead of jQuery. It seems odd since the rest of Bootstrap's scripts are in jQuery. Why is that so? Is it possible to achieve the same functionality wit ...

Guide the user to a specific website and replicate the user's action of pressing the down arrow or clicking a button three consecutive times

Currently, I am facing an issue with a WordPress slider that lacks anchors for linking to specific sections. I am wondering if there is a way to direct a user to a URL and simulate the action of pressing the down arrow or clicking a button multiple times ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...

What is the best way to display a large texture on a small mesh using Three.js?

Having some trouble rendering a texture on a small plane. Imagine I have a texture generated from HTML and rendered as an image. Now, I want to display it on a small plane in VR space near an instrument. The instrument is tiny compared to other objects but ...

Having trouble determining the reason for the error: Invalid element type

Exploring with Next.js and Metamask I'm currently experimenting with connecting Next.js to Metamask in a local setting to retrieve addresses and balances of accounts. My initial step involves creating a simple user interface where I can place a "wal ...

The $.ajax method seems to be experiencing some issues, but fortunately, the $.getJSON

I'm in the process of retrieving the share count for Pinterest and the following code is functioning effectively: var pi_like_count = 0; PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=? ...

The issue of a frozen HTML Bootstrap tab-content link within a nested List-group arises after the initial click

Utilizing a Bootstrap nested list-group, I aim to construct a page navigation element on my HTML page. Upon clicking Home, the webpage should display Link 1, whereas selecting Profile should lead to Link 2. If the user further clicks on Link 1, Page 1 sh ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

Generate an HTML table by utilizing deeply nested JSON information

I am struggling with creating an HTML table from a dynamic nested JSON data structure. Despite my limited knowledge of data manipulation, I attempted various methods without success. The required data is missing in the output. JSON data... https://i.ss ...