Search code examples
javascriptreactjsreduxnext.jssaga

Using redux saga with next.js is anti pattern?


I made a page with next.js like following.

https://github.com/jinhoyoo/breadpan/blob/7db4ba1c458aff4eee558d27c9e7b84af6401596/frontend/todoapp/pages/todo/index.tsx?fbclid=IwAR3gHVcnSDH7R_rqKdN5CtUoKCEo774oESG6QYk3ZpR46RYTS6tlHF9qRHM#L29

Using getInitialProps()set the properties in early time. And it uses asynchronous call too. Then I wonder using redux saga is really usful with next.js.

sampleFetchWrapper() implemented like following.

import fetch from 'isomorphic-unfetch'

export async function sampleFetchWrapper(
  input: RequestInfo,
  init?: RequestInit
) {
  try {
    const data = await fetch(input, init).then(res => res.json())
    return data
  } catch (err) {
    throw new Error(err.message)
  }
}

Here is the post using redux saga with next.js by other person. But I wonder it is right approach or not. Could you recommend the right idea?


Solution

  • It works, maybe only for initial rendering. But SPA is more than that.

    What if you apply a filter on the client side? You will need to get new data with the filter applied. How about writing a comment? You'll need to send a request to the server, get a response, and display the added comment.

    So, using redux-saga is a good approach in case of interacting with the backend after the page is drawn. Use getInitialProps if you want to display content as soon as the user opens the page (instead of showing the loading screen), or if you want to do search engine optimization. Of course, it's also important for faster page rendering.