I am starting to notice a potential problem with the way I am structuring my React application.
I like to architect my components by having one file that acts as a container and multiple stateless components that get passed data and event emitters via props
. This container will contain all the state, API Calls, and event handlers. This container will render child components that are stateless.
Here is an example of a structure I use:
- folder
- index.js <-- container file
- childComponent1.js
- childComponent2.js
- childComponent3.js
- childComponent4.js
...
The size of container file and the number of child components depends on how big a feature is. The problem I had recently was that there was a very big feature that I had to implement, and while I like to use this structure, I started to realize that my container file got very big, like almost 1000 lines of code big. Now, I'm not sure if this is an issue, but seeing 1000 lines of code in one file concerns me. There is just a lot of state to keep track as well as event handlers to read/set new state.
I'm wondering if there are tips on any workaround on this or if there is a different design pattern that I can try and experiment with. Any answer is acceptable!
Thank you!
Wow! I've never seen a single file that big in a react app. You see, having a file that big goes against one of the purposes of using react, in my perspective. The best way to get around this is by using a state management. Passing props up and down (prop drilling) is not ideal will complicate your code. I'd advise you implement some state manager like context or redux.
If your requirements are:
You should use Redux. In a few words Redux:
Go check what it is before using it because there is no consensus. Half of React use it (internet search long ago) and the other half prefer to use built in react solutions like the context to avoid passing data and function through "several layers" of components.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.