Skip to content

Best way to set multiple variables in local storage

I am working on a form for adding a recipe to my website and I want to store the contents of each form input inside of local storage so that they won’t be lost on page refresh. I have around 10 inputs on my form with their contents all held in react states. Would it be better to keep each variable in an object and store that as one local storage item to be changed on every variable state change, or keep each variable in a separate local storage item.

Option 1:

const [a, setA] = useState('')
const [b, setB] = useState('')
// Many more variables...

useEffect(() => {
  const recipes = JSON.parse(localStorage.getItem('recipes'))
  if (recipes) {
    // For each variable...
}, [])

// Update 'recipe' item in local storage on any form input state change
useEffect(() => {
  localStorage.setItem('recipe', JSON.stringify({a, b}))
}, [a, b])

Option 2:

// Set each state to it's local storage item or an empty string if local storage is empty
const localA = localStorage.getItem('a')
const [a, setA] = useState(JSON.parse(() => (localA ? localA : '')))
const localB = localStorage.getItem('b')
const [b, setB] = useState(JSON.parse(() => (localB ? localB : '')))

// Set each individual local storage item on state change
useEffect(() => {
  localStorage.setItem('a', JSON.stringify(a))
}, [a])

useEffect(() => {
  localStorage.setItem('b', JSON.stringify(b))
}, [b])

I just want to know what will be the best for a larger amount of variables or if there is even still a better way to go about solving this in the first place. Thanks a lot!


If you keep the form state in object form you’ll have to serialize it to put it into local storage, so there’s some cost with serializing and deserializing that object. The alternative of storing each field’s value independently wouldn’t have this deserialization overhead. I don’t think the overhead of serialization is a concern for a simple form, so I’d take the object approach.

Perhaps an intermediate would be to use the form object approach, but only persist it when the window is being closed or unloaded.

window.onclose = () => {
    // Save the form state to local storage.