Search code examples
reactjsreduxreact-reduxnext.jsserver-side-rendering

Is using Redux with Next.js an anti-pattern?


I'm building a Next.js app and it currently is using Redux. As I am building it I am wondering if the use of Redux is really necessary and if its use is actually an anti-pattern. Here is my reasoning:

In order to properly initialize the Redux Store in Next.js, you must create a custom App component with a getInitialProps method. By doing this you are disabling the Automatic Static Optimization that Next.js provides.

By contrast, if I were to include Redux on the client-side, only after the App has mounted, then the Redux store will reset after every server-side navigation. For instance, I have a Next.js app that initializes the Redux store on the client-side, but when routing to a dynamic route such as pages/projects/[id], the page is server-side rendered, and I have to re-fetch any information that was in the store.

My questions are:

  1. What are the benefits of a Redux store in this circumstance?
  2. Should I initialize the store in the root App component and forego the Automatic Static Optimization?
  3. Is there a better way to do to manage state in Next.js 9.3 with getStaticProps and the other data fetching methods
  4. Am I missing something?

Solution

  • If you have a custom App with getInitialProps then the Automatic Static Optimization that Next.js provides will be disabled for all pages.

    True, if you follow this approach.

    Is there a better way ?

    Yes, you can create a Redux Provider as a wrapper and wrap the component you need, the redux context will be automatically initialized and provided within that component.

    Example:

    const IndexPage = () => {
      // Implementation
      const dispatch = useDispatch()
      // ...
      // ...
      return <Something />;
    }
    
    IndexPage.getInitialProps = ({ reduxStore }) => {
      // Implementation
      const { dispatch } = reduxStore;
      // ...
      // ...
    }
    
    export default withRedux(IndexPage)
    

    You have now the possibility to use Redux only for the pages which need state management without disabling the optimization for the entire App.

    Answering you question "Is using Redux with Next.js an anti-pattern?"

    No, but it needs to be used properly.

    More info on how is done here: https://github.com/vercel/next.js/tree/canary/examples/with-redux

    I hope this helps