use-memory-storage
v0.0.2
Published
React hooks for memory storage is sharing session storage between multiple tabs.
Downloads
2
Maintainers
Readme
Use Memory Storage
React hooks for memory storage is sharing session storage between multiple tabs. Ideas from the blog post written by @guy-a
Installation
$ npm i -S use-memory-storage
Use cases
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;