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.

4
  • Does this answer your question? How to handle dependencies array for custom hooks in react Commented Apr 28, 2023 at 8: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. Commented Apr 28, 2023 at 9:18
  • What you did is right, The first hook is wrong or more that it is not really the right way doing this. Commented Apr 28, 2023 at 9: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. Commented Apr 28, 2023 at 10:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.