'updating a useState to the value that it's already holding inside of a custom React hook causes infinite re-render

function useHandleURL(mode, page) {
  const [is_page_hidden, set_is_page_hidden] = useState(true);

  ...

  set_is_page_hidden(true);
}

The above will cause an infinite re-render.

I had to solve by doing this:

function useHandleURL(mode, page) {
  const [is_page_hidden, set_is_page_hidden] = useState(true);

  ...

  if (!is_page_hidden) {
    set_is_page_hidden(true);
  }
}

This is not the behavior inside of React components. Inside a component, if I set a useState to true when it is already true, then it will not cause re-render.

Can someone confirm this behavior and explain why it causes infinite re-render inside of a Hook but not a Component?



Sources

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

Source: Stack Overflow

Solution Source