usehooks icon indicating copy to clipboard operation
usehooks copied to clipboard

useLocalStorage does not set initial value!

Open doublejosh opened this issue 5 years ago • 2 comments

The init value of useLocalStorage is not actually saved to localStorage!

import { useLocalStorage } from 'use-hooks'

export const randomHash = () => Math.random().toString(36).substr(2, 9)

const MyComponent = () => {
  const [persistant, setPersistant] = useLocalStorage('persistant', randomHash())
  console.log(persistant)
}
export default MyComponent

The above will result in a new value every page load. You must set the value manually for it to be saved.

doublejosh avatar May 14 '20 23:05 doublejosh

It's more like a default value than an init value.

doublejosh avatar May 14 '20 23:05 doublejosh

I agree with you, there are other problems with this example hook. This is a simple version that uses store.js, does what you would expect.

import { useState, useEffect } from 'react';
// store.js wrapper for errors and fallbacks
import store from 'store';
// const { get, set } = store;
export default function useLocalStorage(key, initialValue) {
	const [state, setState] = useState(store.get(key) || initialValue);

	// Only persist to storage if state changes.
	useEffect(() => {
		// persist to localStorage
		store.set(key, state);
	}, [state, key]);

	return [state, setState];
}

ChristianDavis avatar Jun 04 '20 20:06 ChristianDavis