Skip to content

Instantly share code, notes, and snippets.

@Falci
Last active May 1, 2020 17:24
Show Gist options
  • Save Falci/0acfb7f53cb923ee34e3abbb2303b219 to your computer and use it in GitHub Desktop.
Save Falci/0acfb7f53cb923ee34e3abbb2303b219 to your computer and use it in GitHub Desktop.
import { useReducer } from "react";
const stored = localStorage.getItem("data");
const emptyStore = { ... };
const initialState = (stored && JSON.parse(stored)) || emptyStore;
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error('Unknown action type');
}
};
export const useStorage = () => {
const hook = useReducer(reducer, initialState);
localStorage.setItem("data", JSON.stringify(hook[0]));
return hook;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment