overleaf/services/web/frontend/js/infrastructure/persisted-state-hook.js
Timothée Alby 2ca6d2dadb Merge pull request #3430 from overleaf/msm-filetree-open-selected-entity
[ReactFileTree] Use Local Storage for Open/Closed state of folders and selected doc

GitOrigin-RevId: 55073c92fef6c6e1d538a42b22d60d8657b92153
2021-01-08 03:05:18 +00:00

25 lines
638 B
JavaScript

import { useState, useCallback } from 'react'
import localStorage from './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