React hooks for memory storage is sharing session storage between multiple tabs. Ideas from the blog post written by @guy-a
$ npm i -S use-memory-storage
import React, { useState, useEffect, useCallback } from 'react';
import useMemoryStorage from 'use-memory-storage';
const KEY = 'TEST/useMemoryStorage';
const Demo: React.FC = () => {
const [token, setToken] = useState<string | null>(null);
useMemoryStorage(KEY, token, setToken);
const handleClick = useCallback(() => {
setToken(Date.now().toString());
}, []);
useEffect(() => {
const storedData = sessionStorage.getItem(KEY);
if (storedData != null) {
setToken(storedData);
}
}, []);
useEffect(() => {
if (token != null) {
window.sessionStorage.setItem(KEY, token);
}
}, [token]);
return (
<div>
<p>
Click button to generate token in session storage!
</p>
<output>
stored data : {token}
</output>
<br />
<button onClick={handleClick}>
Click
</button>
</div>
);
}
export default Demo;