Skip to content

Latest commit

 

History

History
61 lines (50 loc) · 1.49 KB

README.md

File metadata and controls

61 lines (50 loc) · 1.49 KB

Use Memory Storage

React hooks for memory storage is sharing session storage between multiple tabs. Ideas from the blog post written by @guy-a

npm version Build Status

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;