5 ms·
Something I often want to do is write a custom hook with internal state that will be used by two or three components - and what I really want to do is have cons
by thrwy_918 5y ago
Something I often want to do is write a custom hook with internal state that will be used by two or three components - and what I really want to do is have consistent internal state for that hook, regardless of which component its being invoked from.
This obviously doesn't work with vanilla hooks, but is there a way to achieve this pattern? It seems like it would be so light and fast compared to a heavier solution
- ngoel36 5y agoRedux is a game changer here https://easy-peasy.vercel.app/docs/api/create-store.html https://easy-peasy.vercel.app/docs/api/create-store.html
- acemarke 5y agoI'm biased, but I would strongly recommend using our official Redux Toolkit package rather than Easy-Peasy: https://redux-toolkit.js.org https://redux-toolkit.js.org
- ngoel36 5y agoCurious, why? (I admittedly know very little here)
- acemarke 5y agoBelated answer, but several reasons: - I created Redux Toolkit :) - It's also "official", ie, from the actual Redux team (myself, Lenz Weber, Tim Dorr) - RTK simplifies common Redux patterns, but tries to stay "typically Redux". It doesn't hide the fact that you're using Redux. Libraries like Easy-Peasy and Rematch add additional levels of abstraction, to the point that it doesn't even look like Redux any more. I can understand why that might be appealing to some folks, but I think it's too much abstraction.
- chrisfosterelli 5y agoThis is what react context is for. You can create helper hooks to expose the context more conveniently. EDIT: I threw together a small example if it helps: https://gist.github.com/chrisfosterelli/2e523b4beae43f05624920b26bb55fa0 https://gist.github.com/chrisfosterelli/2e523b4beae43f056249... It's slightly overengineered in that not everything has to be in separate files; I just reduced this from an an existing example that was more complicated and had this file structure already.
- thrwy_918 5y agothank you!
- chrisfosterelli 5y agoyou're welcome! happy coding
- ishjoh 5y agoWhen we need a custom hook to have consistent state across calling components we have always used a context: https://reactjs.org/docs/context.html#when-to-use-context https://reactjs.org/docs/context.html#when-to-use-context
- frosted-flakes 5y agoYes, with Context. You will need to wrap part of the tree with that Context's Provider, and then you can consume the context value with React.useContext inside a component. Your custom hook can also use this.