Skip to content

Instantly share code, notes, and snippets.

@TortleWortle
Last active November 17, 2018 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TortleWortle/b44d7925dedbdfab9928ea4e65040cdc to your computer and use it in GitHub Desktop.
Save TortleWortle/b44d7925dedbdfab9928ea4e65040cdc to your computer and use it in GitHub Desktop.
ReactJS Custom hook for syncing state between tabs and persist to localStorage.
import { useEffect, useState } from "react";
export const useStorageArea = storageArea => (key, initialValue) => {
const [item, setValue] = useState(
() => JSON.parse(storageArea.getItem(key)) || initialValue
);
const updateFromEvent = e => {
if (e.key === key && e.storageArea === storageArea) {
setValue(JSON.parse(e.newValue));
}
};
useEffect(() => {
storageArea.setItem(key, JSON.stringify(item));
});
useEffect(() => {
window.addEventListener("storage", updateFromEvent);
return () => {
window.removeEventListener("storage", updateFromEvent);
};
});
return [item, setValue];
};
export const useStorageState = useStorageArea(window.localStorage);
export const useSessionState = useStorageArea(window.sessionStorage);
@TortleWortle
Copy link
Author

I don't recommend anyone using this. I made it purely to test things out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment