3 ms·
If you're looking to retrofit something like this in, just for a simple piece of state like which tab is active, and don't want to refactor all your existing lo
by davnicwil 7y ago
If you're looking to retrofit something like this in, just for a simple piece of state like which tab is active, and don't want to refactor all your existing local state management code, Context is a really powerful tool for this.
I think of it like a dedicated state 'portal' - should I need to use one particular piece of local state in other components, I just write a quick dedicated Context for that one piece of data (super quick and simple and React-y using the new API) and simply set the context as well whenever I set that piece of state.
Won't work for everything, is a little hacky in a way and you wouldn't do it that way from scratch, but it's such a quick and easy solution to this issue compared to a major redesign of the global/local state.
- williamdclt 7y agoAgreed, I use Context as a "store for UI stuff" and it always fitted perfectly. Keep data in the global store (Redux or whatever), component-specific state in the local state and inter-component state in Context. And I wrap almost everything in hooks anyway, so the component doesn't care if it's local, Context or Redux: it's just data and I'm free to move it in different stores. Tabs are typically the sort of thing that makes me think "context" immediately. Also implemented nested collapsable sections with this, TikTok-like feed where different components control the same UI component (sliding panel), tables...