mirror of
https://github.com/overleaf/overleaf.git
synced 2024-11-07 20:31:06 -05:00
233ceb5356
* Allow function value in usePersistedState * Add tests for usePersistedState * Use nullish coalescing to avoid calling getItem twice GitOrigin-RevId: e0351addea904aefb7a402bff32689792b49fbbb
30 lines
755 B
JavaScript
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
|