DEV Community

sunflowerseed
sunflowerseed

Posted on

1

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: https://codesandbox.io/s/festive-platform-kjx5u

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more