Reputation: 3139
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
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