'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) {
    setA(recipes.a)
    setB(recipes.b)
    // 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!



Solution 1:[1]

You can use multiple variables,

If you want to minimize the serialization just use this helper file to reuse the functionalities and to have your code clean.

Helper file: https://gist.github.com/scrubmx/a240a912a475ab0a2c43

If you are going to build a larger app with redux state management, I will strongly recommend you to use redux-persist. You no need to worry about serializing and deserializing. There are a lot of features you can use.

Documentation: https://www.npmjs.com/package/redux-persist

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Srimurugan Subramanian