DEV Community

Discussion on: Conditional hooks, maybe

Collapse
 
devdufutur profile image
Rudy Nappée • Edited

Indeed you should't get your Hook in a conditionnal way.

Not sure what you wanna do exactly but you can create a custom Hook like that :

function useStateWithPersistance(initialValueIfNotFound) {
  let initialValue = initialValueIfNotFound;
  try {
    initialValue = localStorage.getItem("whatever");
  } catch {}

  const [whatever, setWhatever] = useState(initialValue);

  function setWhateverWithPersistance(val) {
    try { 

       localStorage.setItem("whatever", val);
    } catch (e) {}
    setWhatever(val);
  }

  return [whatever, setWhateverWithPersistance];
}
Collapse
 
devdufutur profile image
Rudy Nappée • Edited

You can then use it like a useState.

And you can generalize the name of the storage key as a second parameter of your custom hook in order to reuse you hook anywhere you want.

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Thank you, but the persist library did much more then just saving into the localstorage there was debouncing and much more, now the library is updated and the temporary fix is not used anymore.