[BUG] useLocalStorage's setValue should be callable in render phase (like a normal `useState`)

Author: jraoultCreated Mar 19, 2024Updated Apr 14, 2026
Labelsbug

Describe the bug

Calling the setter of useLocalStorage in a render phase triggers the error with the message Cannot call an event handler while rendering.. It is because useEventCallback is used internally, but I think useCallback should be used instead since it is not conceptually only an event handler.

To Reproduce

See the reproduction sandbox, but the gist of it is:

typescript
import { useEffect, useState } from 'react';
import { useLocalStorage } from 'usehooks-ts';

function App() {
  const [count, setCount] = useState(0);
  const [lsCount, setLsCount] = useLocalStorage('lsCount', 0);

  if (count === 0) {
    setCount(1);
  }

  // if (lsCount === 0) {
  //   // this should work but fails right now
  //   setLsCount(1);
  // }

  // this is the workaround
  useEffect(() => {
    if (lsCount === 0) {
      setLsCount(1);
    }
  }, [lsCount]);

Expected behavior

It should be possible to set a value in the render phase.