Sharing State Among React Components
When it comes to sharing data (state) between components, the traditional React approach to this is to Lift State Up and Send Props Down.
Imagine you have two components inside some container.
- One renders a tree-view of a folder structure.
- The other renders a list of files.
Now imagine that you want critical information to be shared/communicated between the two. Perhaps your intent is for the list of files to be the files of some folder selected in the other component. How would you share that information? One simple approach is to move (lift) the state from the children and put it in the parent. Here’s the steps in a nutshell.
- Identify what state needs to be shared among the components. It might be all the state, or only part of the state.
- Move the storage of the state from the child(ren) to the parent.
- Pass the state from the parent to the child(ren) via props.
The final result is
| Before Sharing | After Sharing |
|---|---|
Note that this is not the only way to share state among components. But it’s been a common enough pattern that the process is documented in detail on React’s website.
See the official React docs on Sharing State