'React: Update a self-contained grandchild from a click even from grandparent
I currently have the following situation:
<GrandParent> // click happens here
<Parent>
<Child> // self-contained with its own state
Is there a way to update the react state inside of the child with a click in the GrandParent? I hate having all this Child-specific code in GrandParent. Right now, the only way I know to make the code functional is to pull all state into GrandParent and make state changes when the click happens, then pass that state into the child (vis useContext hook).
Update: So I researched this further and yes, I could use solutions like redux, however this feels overkill for a small app. I did find some non-library solutions that might be a good fit for anyone looking at this question in the future.
The following solution uses 'this' binding. It works even if it's a bit janky. But the downside is that you have a global name space pollution and The grandparent has to have access to the grandchild, which I don't (it's on a different 'page'). https://www.codeproject.com/Tips/1215984/Update-State-of-a-Component-from-Another-in-React
This approach uses an event emitter to signal when a state change should happen. It's pretty clean but uses a library, albeit a tiny one. I like this approach, however, it doesn't feel very 'reacty'. https://medium.com/@krzakmarek88/eventemitter-instead-of-lifting-state-up-f5f105054a5
Finally, I ended up using this solution. The gist is that instead of using a react context for storing state, you use the context to store functions that trigger state changes. Since the callbacks don't change themselves, you avoid unnecessary redraws and the solution stays within the bounds of normal react. https://javascript.plainenglish.io/dispatch-an-action-to-update-a-sibling-within-react-e98f5b5041f3
Solution 1:[1]
You could use a top-level state management tool like React Redux: https://react-redux.js.org/introduction/getting-started
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bilbo baggins |
