I was working with someone else's code and there was custom hook:
const {
data, loading,
count, mutate
} = useSomeoneHook(filter, page, pageSize);
/* file with hook */
const useSomeoneHook = (filter, page, pageSize) => {
const { data, error, mutate } = fetch(filter, page, pageSize);
return {
filter: data,
count: data.count,
loading: !error && !data,
mutate
};
I thought it should run every time one of filter/page/pageSize state variables changes (I suspect that this was desired behavior). But I debugged it and I saw that this hook runs even when I update another state variable, let's say setSomeVariable(false)
.
So hooks runs on each rerender and if I want to create hook that runs when some variable change I need to use useEffect inside of my hook and pass variables to dependency array?
So it should look something like that?
const useSomeoneHook = (filter, page, pageSize) => {
const [data, setData] = useState({})
useEffect(() => {
const result = fetch(filter, page, pageSize);
setData(result)
}, [filter, page, pageSize])
return {
filter: data.data,
count: data.data.count,
loading: !data.error && !data.data,
mutate: data.mutate
};
} Can someone please confirm this? I'm a little bit confused right now. Thank you.