getFromLocalStorage

Get data stored in the local storage with a fallback to null


Avoid error if window has not loaded


Code

getFromLocalStorage.tsx
export function getFromLocalStorage(key) {
  if (typeof localStorage !== 'undefined') {
    return localStorage.getItem(key);
  }
  return null;
}

Usage

const [token, setToken] = useState(() => getFromLocalStorage('token') || null);

See all posts