Hacker News new | ask | show | jobs
by AWebOfBrown 2983 days ago
I think it makes more sense if you start thinking outside the Toggle component itself.

For passing down the state to the actual button(s), as Kent says, you could just use React.Children.map(). When you think about consuming that state from other components that need to know the toggle state, things get a bit messier, as many of those components might not be direct children of the actual <Toggle />. Maybe the toggling affects something in your navbar, for example.

In that case, the alternative to using context would be a global store, where the state provider sits above all components (think Redux, MobX).

If you're only consuming the toggle state from child / grandchild / sibling etc. components, the alternative typically involves passing down the toggle state from some parent / grandparent component, which means passing this.state.toggled down 2+ levels, instead of simply importing the context's consumer and subscribing where needed.

Context is now a reasonably simple and clean alternative to those options, but this example leaves envisioning the pain alleviated as an exercise for the reader.

1 comments

Fair enough, I suppose. I still think the additional complexity of having to bring in the context for the save of passing 1 variable through the whole tree is overkill though.
I'm developping a web app with fairly complex forms (imagine form sections, form templating...). The immediate use case of Context that comes to mind would be to pass down the `readonly` prop from the top-level Form component all the way down to the Field component, without having to drill through `FormSection`, `Template`, `TemplateSection` or any other component between the Form and the Field.
In the case of a form, what’s wrong with composing a whole tree of custom “presentation” components in one render? Does this take up too much space?

You don’t always need to pass the prop through each individual component, instead you can render a section (or the whole form) together as one larger context-specific UI component, where everything in the render call has access to the same prop values.

That's entirely true. It becomes much more applicable where there's more complex state that's used throughout an application.