Skip to content

Instantly share code, notes, and snippets.

@garikaijenje
Last active April 10, 2021 19:46
Show Gist options
  • Save garikaijenje/6532f5dec2d23e5cd5f35658f2f82900 to your computer and use it in GitHub Desktop.
Save garikaijenje/6532f5dec2d23e5cd5f35658f2f82900 to your computer and use it in GitHub Desktop.
Custom react hook to persist your states
import React, { useState, useEffect } from "react";

const usePersistedState = (key, defaultValue, stringified = false) => {
  const [state, setState] = useState(
    () => (stringified ? JSON.parse(localStorage.getItem(key)) : localStorage.getItem(key) ) || defaultValue
  );
  useEffect(() => {
    localStorage.setItem(key, stringified ? JSON.stringify(state) : state);
  }, [key, state]);
  return [state, setState];
};

export default usePersistedState;

stringified is an optional third parameter to indicate if your state is stringified or not.

Example Usage

const [data, setData] = usePersistedState('myData', {}, true); // data is stringified
const [token, setToken] =  usePersistedState('myToken', null);

setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment