How to refresh a React component when local storage has changed

Whenever I want to quickly prototype an application and there’s no need for a database yet, I usually use local storage as a place to store all kind of data. This solution is especially useful when I just want to share certain functionalities and nothing has to be stored for the future reference.
If you want to refresh a React component when local storage changes, look no further!
First, make sure that you fire an storage event. Making changes to elements stored in the local storage don’t trigger it. In order to make it work, invoke appropriate event after changes to the local storage were made.
localStorage.setItem('key', 'value') window.dispatchEvent(new Event('storage'))
Then, to refresh an functional component whenever a new storage event is invoked, I highly recommend using the useEffect hook. By setting it up with an additional addEventListener method inside, we can easily display changes made to the local storage.
import { useEffect } from 'react' useEffect(() => { const handleStorage = () => { // Place for a function responsible for // pulling and displaying local storage data } window.addEventListener('storage', handleStorage()) return () => window.removeEventListener('storage', handleStorage()) }, [])
In our case, useEffect hook allows us to append an event listener to the component. For further reference I heartily recommend reading a Using the Effect Hook article from the React documentation.
Upper snippet roughly translates to the code below when used in the class component.
const handleStorage = () => { // Place for a function responsible for // pulling and displaying local storage data } componentDidMount(() => { window.addEventListener('storage', this.handleStorage) } componentDidUnmount(() => { window.removeEventListener('storage', this.handleStorage) }