3 ms·
Just like jQuery can lend itself to spaghetti code, but can also be a basis for scalable web apps (I have fond memories of the Backbone.js era!)... React can le
by btown 3y ago
Just like jQuery can lend itself to spaghetti code, but can also be a basis for scalable web apps (I have fond memories of the Backbone.js era!)... React can lend itself to a strong coupling between hierarchy and state management, and that's what many projects using "just React" will gravitate towards. But it's also possible to separate those concerns in the React ecosystem.
If you look at systems like React Redux, and the general pattern of a central store to which different pieces of code can subscribe to, it's perhaps the thing that is closest to ECS on the frontend.
See https://redux.js.org/understanding/thinking-in-redux/three-principles https://redux.js.org/understanding/thinking-in-redux/three-p... and the examples at: https://react-redux.js.org/api/hooks#useselector-examples https://react-redux.js.org/api/hooks#useselector-examples
Rather than drilling state through hierarchical props, one can create a specification for a TodoListItem that has it subscribe to the "todos" part of storage, and rerender when that changes. And then you have a separate "system" (using the word both figuratively and in the ECS way!) that responds to UI input or network traffic, updates some isolated global state that only that system controls (say, the "todos"), and notifies all entities that are subscribed to the derived state.
So then, a React functional component that religiously uses Redux (or a similar external storage system) for state management becomes akin to an ECS-entity whose set of ECS-components corresponds to which Redux useSelector and useDispatch hooks it chooses to use. And the ECS-systems are what mutate state in response to dispatched actions - you just need to make sure they have good boundaries.
If you adhere to this, the parent-child relationship between components really doesn't matter; you could nest a TodoListItem just about anywhere and it would behave the same. It's just that in web dev it's so common to say "I am the box for an ordered list of things, and as I move and reshape my children should do the same" that while you could in theory have an ECS system that track hierarchies and repositions children using JS as the parent moves, it's more natural to do something a bit more hybrid and allow the natural DOM hierarchy to control certain things - but not all.