Skip to content

React hooks for memory storage is sharing session storage between multiple tabs.

License

Notifications You must be signed in to change notification settings

wonism/use-memory-storage

Repository files navigation

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;

About

React hooks for memory storage is sharing session storage between multiple tabs.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published