I’m working on a React project and I’m a little confused as to how to structure my component with multiple states and complex logic. The following is the component structure:
component
│ component.tsx
│ component.scss
|
└───childComponent1
│ │ childComponent1.tsx
│ │ childComponent1.scss
│
└───childComponent2
| │ childComponent2.tsx
| │ childComponent2.scss
|
└───sharedGrandchildComponent
| │ sharedGrandchildComponent.tsx
| │ sharedGrandchildComponent.scss
|
└───hooks
| │ useA
| │ useB
| │ useC
| │ useD
grandchild component is shared between child components. I’m sure there’s a better way to structure this but that’s not my primary concern at the moment. My question is more to do with the structuring of states for this whole component. The way I see it, there are 4 different ways to organize this:
- Keep all the useStates & useEffects in the main component: Terrible idea. There’s really no organizing here and my component will be heavier than a brick.
- Define each state in its respective custom hook in the main component, then implement useContext to pass these values down to children components: This allows me to move state logic into the custom hooks, so much better than Option 1. The only problem I have with Option 2 is that if I have a useEffect hook where update of state A depends on state B, I need to pass state B into useA hook. That doesn’t seem like a great idea. Which brings me to…
- Implement useReducer to merge the states for this component: This seems like a good idea, but I’m using a lot of editors for this page that update states real time, and I don’t think making them update this giant object (instead of individual states) every time the user types is a good practice. (Correct me if I’m wrong though)
- Store all these states in redux store: This seems to be the best approach so far. I would leave all the states in the central store for this component’s slice, provide them at this component’s level, and use reducers in the store to use the states right from the store without having to pass them down to the children components. My only concern here is that since these states are very specific this component, I wish I could have found a way to contain them at this component’s level.
I understand this is a rather high-level discussion and not necessarily a specific issue anyone can 100% help me with without knowing more details (even though I tried to provide as much info as possible). Any comment/suggestion would be appreciated!