0

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.

Patryk
  • 29
  • 5
  • Does this answer your question? [How to handle dependencies array for custom hooks in react](https://stackoverflow.com/questions/56262515/how-to-handle-dependencies-array-for-custom-hooks-in-react) – possum Apr 28 '23 at 08:47
  • custom hook is a function at the end. And you are calling it, of course it will execute. React does not do magic, it just calls again your function component, and since you are calling your hook , there is nothing strange in that it executes on each render. – Oktay Yuzcan Apr 28 '23 at 09:18
  • What you did is right, The first hook is wrong or more that it is not really the right way doing this. – Alen.Toma Apr 28 '23 at 09:32
  • It depends on what `fetch` is/does. It doesn't seem to be `async` so I'd assume that it's not just a request to the backend but also does some caching/internal state management. But then I don't see a way for `fetch` to tell react when the inevitable async part is done. Unless it's mutating the object it's returning, which comes with it's own set of problems. So summary: there are questions. – Thomas Apr 28 '23 at 10:00

0 Answers0