react-awesome-router icon indicating copy to clipboard operation
react-awesome-router copied to clipboard

`useLocation` callbacks not referentially stable

Open Nirei opened this issue 2 years ago • 0 comments

Repeated renders of a component using useLocation return new instances of setContext and setLocation. This makes it very dangerous to use this functions as they can easily trigger re-renders if you are not careful.

See for example this code:

  useEffect(
    () => setContext({ owned, installed }),
    [setContext, owned, installed],
  )

The setContext has been wrapped in a useEffect to prevent continuous triggering of setContext to retrigger full <Routes /> re-render. This fails because the effect is relaunched on every render since setContext changes to a new pointer on each render.

To prevent this, setContext and other router callbacks should be a stable ref.

Nirei avatar May 16 '22 08:05 Nirei