Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3139

Transform function to useCallback

I want to rewrite a function like:

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

to preferred by React useCallback form, my best guess was:

const useQuery = useCallback(
  () => {
    return new URLSearchParams(useLocation().search);
  },
  [useLocation]
);

The error which I got:

React Hook "useLocation" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

Does it mean that I cannot transform my function to useCallback?

Upvotes: 1

Views: 1568

Answers (1)

David
David

Reputation: 218837

useLocation is a hook and should be called directly in the component. Its result however can be used in a callback. For example:

const location = useLocation();
const useQuery = useCallback(
    () => {
        return new URLSearchParams(location.search);
    },
    [location]
);

Though since location is an object and you really only care about the search value, the comparison to determine what's changed for the useCallback hook is likely more accurate with just the simple value:

const { search } = useLocation();
const useQuery = useCallback(
    () => {
        return new URLSearchParams(search);
    },
    [search]
);

Upvotes: 2

Related Questions