overleaf/services/web/frontend/js/shared/hooks/use-persisted-state.js
Alf Eaton 233ceb5356 Allow function as value for usePersistedState hook (#5131)
* Allow function value in usePersistedState
* Add tests for usePersistedState
* Use nullish coalescing to avoid calling getItem twice

GitOrigin-RevId: e0351addea904aefb7a402bff32689792b49fbbb
2021-09-24 08:04:21 +00:00

30 lines
755 B
JavaScript

import { useState, useCallback } from 'react'
import localStorage from '../../infrastructure/local-storage'
function usePersistedState(key, defaultValue) {
const [value, setValue] = useState(() => {
return localStorage.getItem(key) ?? defaultValue
})
const updateFunction = useCallback(
newValue => {
setValue(value => {
const actualNewValue =
typeof newValue === 'function' ? newValue(value) : newValue
if (actualNewValue === defaultValue) {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, actualNewValue)
}
return actualNewValue
})
},
[key, defaultValue]
)
return [value, updateFunction]
}
export default usePersistedState