0

According to the documentation of SWR: React Hooks for Data Fetching, there is an options object which can be passed in for more control of the hook.

The documentation mentions a compare option:

compare(a, b): comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, dequal is used.

Is it something like this?

export function useUser(shouldAPIBeCalled = false) {
  const { data: user, error, mutate } = useSWR(() => shouldAPIBeCalled ? '/api/user' : null, fetcher, {

  compare: (_old, _new) => {
    return dequal(_old, _new);
  }
})

Essentially I don't want the fetcher to be called if we haven't changed the original object in my case:

If the user is still...

user: null // don't make that call again

Don't make another call because it hasn't changed!

What’s happening to me is the hook keeps firing.

I only have the hook in a Layout component to show hide navigation elements if we have a user or not,

In the submit function of the login to get the mutate function to update the user,

And in the Auth component (which wraps certain pages) to check if a user is authorized.

Thanks in advance!

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • 1
    The check you want to make already happens by default using [`dequal`](https://github.com/lukeed/dequal). If `data` was `null` before and is `null` again the re-render won't happen, however the request will still happen either way as the compare function runs _after_ it. – juliomalves Dec 08 '21 at 16:54
  • Thanks for that. So it's normal the `useUser(true)` will keep firing. Right? But that is because one is in `Layout` component and the other is in the `AuthCheck`? Right? This is the repo.. `https://github.com/antonioOrtiz/hillfinder/tree/master` – Antonio Pavicevac-Ortiz Dec 08 '21 at 17:10

0 Answers0