Do two React components need a global store?
When two nearby components need the same value, start with their closest shared parent. One owner removes the need to synchronize two local copies.
The value follows its owner’s lifetime. A bookmarkable tab may belong in the URL; distant consumers or different lifetimes can justify another design.
Understand it. Then fix it.
Start with one owner.
Usually, lift the value to their closest shared parent. Both read the same value, and the toolbar asks that parent to update it.
One value. Two readers.
Here, the page owns tab. Selecting Activity updates that one value, so the toolbar and panel agree. There are no two copies to synchronize.
const [tab, setTab] =
useState("details");
return <>
<Toolbar tab={tab}
onChange={setTab} />
<Panel tab={tab} />
</>;Match the owner to the lifetime.
If only that page needs it, keep it there. Removing that owner resets its local state. A bookmarkable tab may belong in the address instead.
Share farther when necessary.
For distant descendants, Context can pass the value. A shared store fits independent consumers across the app. Decide who reads it and how long it must live first.
<TabContext value={tab}>
<PageContent />
</TabContext>Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
Two components need the same selected tab. Do I need a global store, or am I installing a board of directors for a button? Usually, lift the value to their closest shared parent. Both read the same value, and the toolbar asks that parent to update it. Here, the page owns tab. Selecting Activity updates that one value, so the toolbar and panel agree. There are no two copies to synchronize. If only that page needs it, keep it there. Removing that owner resets its local state. A bookmarkable tab may belong in the address instead. For distant descendants, Context can pass the value. A shared store fits independent consumers across the app. Decide who reads it and how long it must live first. Two buttons. One value. Somehow we still scheduled a steering committee.