Sobes.tech
Junior — Middle

What parameters can be passed to the useEffect hook to control its execution?

sobes.tech AI

Answer from AI

The React hook useEffect takes two parameters:

  1. The effect function, which runs after the component renders.
  2. An optional dependencies array, which controls when the effect should run.

Parameters for controlling execution:

  • Without the second parameter: the effect runs after every render.
  • Empty array []: the effect runs only once — after the first render (similar to componentDidMount).
  • Array with dependencies [dep1, dep2]: the effect runs after the first render and whenever any dependency changes.

Example:

useEffect(() => {
  console.log('Effect triggered');
}, [props.value]); // runs when props.value changes

Thus, the dependencies array helps optimize effect execution and avoid unnecessary calls.