4

So, I'm planning on doing a Facebook clone to add to my portfolio, and I want to use, react-Next.js, node.js, express.js, typeORM and postgresSQL ( everything in typescript ), but i have a big issue with global state managment

The Question: So, I was thinking, and I said, ok, I'm going to use redux, i know how to use it and i love it, but, to implement redux in next.js, seems QUITE HARD, so, i was i said, well, what if i don't need to use a global state managment ? what if i just use the SWR hook and revalidate data whenever i create/update data in the fronted ? and that might be ok, but is that a bad idea? shouldn't i do that ?

My Goal : Everything i need to know, is, is it bad if i only use SWR or should in try my best implementing redux i next.js? i have those options, but i just don't know what to do, with create-react-app setting up redux is easy, but in next.js i just don't get it, so, if you can help me with your answer, i would thank you a lot !!

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Diego
  • 421
  • 3
  • 9
  • 34
  • 2
    From my experience you should stay a way from Redux in general - especially in Next.js. It's kind bloated and you can just use React Context inside of Next.js for global state when global state is needed (React Context is very nice and people use it a lot with Next). – Caleb Lawrence May 15 '21 at 20:01
  • Regarding when to use SWR and when not to: SWR is super cool but it's mainly for rendering data from an API on your page. So if I want to hit an API to pull the latest stock market stats then I'd use SWR and not put that data into state at all. However if youre dealing with some sort of form or any user input or something like that then you will need actual React State for that (Context or just UseState hook). SWR is only for data fetching on the clientside. – Caleb Lawrence May 15 '21 at 20:03
  • 2
    In summary, SWR is for managing remote state (from an api). UseState is your go to for managing state in a component, and when you need global state (such as info on the user auth that you will need in lots of components) then can use React Context which is very easy to do in Next.js and you can find examples for that everywhere. – Caleb Lawrence May 15 '21 at 20:05
  • All right man ! , i get it, thanks you so much for your answer ! – Diego May 15 '21 at 20:16
  • 2
    While React Context is a great tool for state management, that depends a lot of the size of a state that you have to handle. For a complex state I would definitely go for Redux, but not for this case. We use Next+Redux for production and it works fine. – Fer Toasted Aug 27 '22 at 19:52
  • Thanks for sharing, i actually have been also thinking about zustand to replace redux ! – Diego Aug 28 '22 at 20:51

1 Answers1

2

swr+contextApi is used together to replace redux. This is step by step how you can set it up:

  • create your different hooks. for example

    export const createFirstHook =
        ({ arg1, arg2 }) =>
        () => {
          //   CONDITIONAL USESWR CALL
          // isValidation is true whenever you are retrievnig a new data
          const { data, isValidating, ...swr } = useSWR(
    
                // write fetching logic           
          );
          return {
            ...swr,
            isValidating,
            data,
          };
        };
    
  • in your app, you will have many hooks and combine them like this. Think of this as the main reducer in redux.

      import { createFirstHook} from "./useNetwork";
    
    
      export const setupHooks = (deps) => {
        return {
          useFirstHook: createFirstHook(deps),
          ...
        };
      };
    
  • write your context and include hooks in the returned object.

    const Web3Context = createContext(null)
    
      const createWeb3State = ({arg1, arg2}) => {
        return {
          arg1,
          arg2,
          // Passing hooks here  
          hooks: setupHooks({erg1,arg2})
        }
      }
    
      export default function Web3Provider({children}) {
        const [web3Api, setWeb3Api] = useState(
          // this function will set the hooks
          createWeb3State({
            arg1: null,
            arg2: null,
          })
        )
       // you add more logic
       // eventuallay you return this
        return (
          <Web3Context.Provider value={web3Api}>
            {children}
          </Web3Context.Provider>
        )
      }
    

this is how you reach the provider data in other parts of your app.

 import { useContext } from "react";

 const context= useContext(Web3Context);

This will make you import import { useContext } from "react" ewerwhere you need the context. Instead, in this provider file, you import the useContext and export this function

export function useWeb3() {
  return useContext(Web3Context);
}
  • in next.js you have to wrap the _app.js with the provider

    function MyApp({ Component, pageProps }: AppProps) {
        return (
          <>
            <Web3Provider>
              <Component {...pageProps} />
            </Web3Provider>
          </>
        );
      }
    

Now you can reach your context and hooks anywhere in your app. In this approach each hook function acts like reducers but good thing is you can use those hooks independently somewhere else in your app.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202