I know that in case of react components the function inside useEffect will run after the component has been rendered. When exactly does it run if the useEffect is inside a custom hook?
As a more generic question when do the codes inside a custom hook run when the component using the hook is (re)rendered?
2
Answers
In React, when a component using a custom hook is rendered or re-rendered, the code inside the custom hook runs just like any other function in JavaScript. The useEffect hook inside the custom hook will also run after the component has been rendered, just like when it is used directly inside a component.
To be more specific, the code inside the custom hook will run every time the component using the hook is rendered or re-rendered. This is because the custom hook itself is just a function that is called every time the component is rendered. The useEffect hook inside the custom hook will also run every time the component is rendered or re-rendered, based on the dependencies specified in the useEffect hook.
It’s important to note that the behavior of the custom hook may depend on the state and props passed into it by the component, so the code inside the custom hook may run differently depending on the inputs to the hook.
The code inside a custom hook will be executed whenever the component using the hook is rendered, just like any function.
However, the behavior of useEffect hooks remains the same, i.e. they are only executed when the dependencies specified in their dependency array change.
import React, { useState, useEffect } from "react";