Skip to content

Commit

Permalink
feat(hook): create new custom hook
Browse files Browse the repository at this point in the history
Create usePersistedState hook to save state on local storage
  • Loading branch information
mateusfg7 committed Sep 1, 2020
1 parent 3f28af0 commit bfa2890
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/utils/usePersistedState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useState, useEffect, Dispatch, SetStateAction } from 'react';

type Response<T> = [T, Dispatch<SetStateAction<T>>];

function usePeristedState<T>(key: string, initialState: T): Response<T> {
const [state, setState] = useState(() => {
const storageValue = localStorage.getItem(key);

if (storageValue) {
return JSON.parse(storageValue);
} else {
return initialState;
}
});

useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);

return [state, setState];
}

export default usePeristedState;

0 comments on commit bfa2890

Please sign in to comment.