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

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

Leave a Comment