SoFunction
Updated on 2025-04-07

React Hook listens for localStorage update problem

Scene

The data is stored in localStorage. The localStorage changes to update the data used in the component in real time.

Misconception

What I subconsciously thought of is the useEffect listening to the changes in useState

    useEffect(()=>{
        useData(('rightCartData'))
    },[('rightCartData')])

Obviously not, why?

Reasons why the example does not work:

It is related to the dependency array passed to useEffect, which determines whether to re-run when the component is rendered, which means that if localStorage changes, it must be rendered first.

How to solve this problem:

It is to set up a subscription to localStorage, monitor changes and notify components to re-render

Window: storage event - Web APIs | MDN

Complete solution code

as follows:

useEffect(() => {
        function rightCartData() {
            const item = (('rightCartData'))
            if (item) {
                setState(item);
            }
        }
        ('storage', rightCartData)
 
        return () => {
            ('storage', rightCartData)
        }
    }, [])

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.