DEV Community


Posted on

What if a ReactJS app is structured so that App State is the App container, and App and all components are context consumers?

I wonder if a ReactJS app is structured this way, will it work properly:

  1. All the app state is inside an app context and the App is under AppContainer.
  2. The App and all components can be the context consumers.
  3. Each component has a "data of concern" setter assigned to it.
    • inside the component, every state is local and independent of the component, except when the final value is obtained by user interacting with the component, it is set by the handler from the context to "set the data of concern".
    • for example, each Counter component works independently, and can be implemented by any method, but all the parent and App cares is, when the value is ready, set it into the "data of concern" in the context
  4. This way, the App or any component has access to all the app data, if needed.
  5. The component can set data using these "global data setters", but since those are passed down by props, if there is any error, we can grep for which components might be the one setting the data accidentally easily, just by grep'ing for that setData() callback name.
  6. It does mirror the HTML way: we have different elements, such as input field, date picker <input type="date">, color picker <input type="color">, etc, and we only care what the final value that it provides, and don't really care how it is implemented internally.

A sample is on:

There are 3 counters, and they are independent components, and keep the count for Noodles, Drinks, and Snacks, and set the count into a property in the context when user interacts with the counter.

Top comments (0)