[React] Monitor sessionStorage / localStorage updates

Article Directory

  • At the beginning, I would subconsciously think of using the dependency array of useEffect to directly monitor the change of useState, but the fact is that it doesn’t work
useEffect(()=>{
    
    
    useData(localStorage.getItem('test_data'))
},[localStorage.getItem('test_data')])
  • It can only be monitored through js natively, but it should be noted that:

When the storage area is modified in the context of another document, the storage event will be triggered, but:

  • This doesn't apply to the same page that made the change!
    It's actually a way for other pages on the domain to use the store to sync any changes made.
    Pages on other domains cannot access the same storage objects.
export default function () {
    
    
  const [state, setState] = useState('');
  const click = () => {
    
    
    localStorage.setItem('test_data', String(Math.random()));
  };
  useEffect(() => {
    
    
    console.log('sessionStorage = ', state);
  }, [state]);
  const getStorage = () => {
    
    
    const item = localStorage.getItem('test_data') ?? '';
    console.log('getItem = ', item);
    setState(item);
  };
  useEffect(() => {
    
    
    window.addEventListener('storage', getStorage);

    return () => {
    
    
      window.removeEventListener('storage', getStorage);
    };
  }, []);
  return (<button onClick={
    
    click()} >测试</button>)
}
  • Finally, let's sum up: let's just storeuse it .

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/131459962