Search code examples
reactjsreact-hooksreact-context

React why use useContext over creating many useState hooks


I am trying to create a taxi application and manage the state to reduce re-renders and prop drilling. I currently have 5 tables (Booking, Customer, Driver, Taxi, Review) and am thinking of creating context for each of them which would entail something like below:

<Provider1>
   <Provider2>
      <Provider3>
         <ComponentToRender />
...

However, not every field in each context is required for each of the consumers - meaning unnecessary re-renders will occur. Instead of going through the trouble of implementing the useMemo hook, would it be more efficient to just have a bunch of useState variables?

For example, a useState variable for each of the useContext keys:

userContext: {
   firstName
   lastName
   phoneNumber
   ...(~12 rows)
}

This will reduce re-renders but if this is possible, then what's the point of state management using useContext aside from reducing prop drilling? I feel like it's more for accessing data than managing state data


Solution

  • It's time to use a state management library. I'd recommend recoil

    As you said, because of the way React works, prop drilling causes unnecessary and inevitable re-render. Even if, you use useMemo that doesn't solve the problem completely. Because if the parent's state changed, it will re-render anyway.

    recoil solve those problems. Check this link > https://recoiljs.org/

    You can use your state any components that its in need. And when you update your state, only the components which subscribes the state will re-render.