How can I use localstorage value of benchmarkActiveTab
in the dependency array? The value is changing in the localstorage but the useEffect
isn’t running when the value changes
const [activeTab, setActiveTab] = useState(
localStorage.getItem("benchmarkActiveTab") || 0
)
useEffect(() => {
async function getBenchmarkTimes() {
// this function doesn't run
}
getBenchmarkTimes()
}, [activeTab])
I tried to make the useEffect
run when the localStorage.getItem('benchmarkActiveTab')
changes, but the useEffect doesn’t run.
2
Answers
You need to listen to
storage
eventIn your code, the state
activeTab
is only set once during the initial render. It never changes again. So the effect depends on it will never run again either.You can use
useSyncExternalStore
hook. This hook accept two kind of params:subscribe
andgetSnapshot
. Every timesubscribe
call the callback, React callsgetSnapshot
and gets a fresh snapshot. If the snapshot changes (when result fromObject.is
is false), React rerender the component.See full example here.