Handling Storage Events Across Tabs
React to localStorage changes in other browser tabs using the storage event listener.
The Cross-Tab Staleness Problem
When a user has your app open in two tabs and updates a value in tab A, tab B still shows the old state. Each tab has its own React state in memory even though they share localStorage.
Without coordination, the tabs disagree about the current value.
The storage Event Fires in Other Tabs
The browser dispatches a storage event on other tabs of the same origin whenever localStorage changes. Importantly, it does not fire in the tab that made the change.
This is exactly the signal tab B needs to learn that tab A updated something.
All lessons in this course
- Reading and Writing localStorage in React
- Syncing State with localStorage
- Handling Storage Events Across Tabs
- sessionStorage, IndexedDB, and Choosing the Right API