usehooks
usehooks copied to clipboard
useLocalStorage does not set initial value!
trafficstars
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.
It's more like a default value than an init value.
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];
}