mirror of
https://github.com/overleaf/overleaf.git
synced 2024-12-13 07:39:22 -05:00
8c3578e74b
Rename hooks files and move to shared folder GitOrigin-RevId: 9659247b5e767197c3e11acc9a3922ecaab49162
25 lines
657 B
JavaScript
25 lines
657 B
JavaScript
import { useState, useCallback } from 'react'
|
|
import localStorage from '../../infrastructure/local-storage'
|
|
|
|
function usePersistedState(key, defaultValue) {
|
|
const [value, setValue] = useState(() => {
|
|
const keyExists = localStorage.getItem(key) != null
|
|
return keyExists ? localStorage.getItem(key) : defaultValue
|
|
})
|
|
|
|
const updateFunction = useCallback(
|
|
newValue => {
|
|
if (newValue === defaultValue) {
|
|
localStorage.removeItem(key)
|
|
} else {
|
|
localStorage.setItem(key, newValue)
|
|
}
|
|
setValue(newValue)
|
|
},
|
|
[key, defaultValue]
|
|
)
|
|
|
|
return [value, updateFunction]
|
|
}
|
|
|
|
export default usePersistedState
|