Sobes.tech
Junior

What is the use of the useEffect hook in React?

sobes.tech AI

Answer from AI

useEffect in React is a hook that allows you to perform side effects in functional components. Side effects include:

  • Direct manipulation of the DOM.
  • API requests.
  • Subscribing and unsubscribing from events.
  • Timers.

useEffect takes two arguments:

  1. Effect function: Executed after each render of the component, if no dependency array is specified.
  2. Dependency array (optional): Determines when the effect should re-run based on changes in specified values (state, props).

Examples of usage:

Without a dependency array (executes after every render):

useEffect(() => {
  // Effect code
});

With an empty dependency array (executes only after the first render, like componentDidMount):

useEffect(() => {
  // Effect code
}, []);

With a dependency array (executes on first render and when values.value1 or values.value2 change):

useEffect(() => {
  // Effect code
}, [values.value1, values.value2]);

The effect function can return a cleanup function, which runs before the next effect or before the component unmounts (like componentWillUnmount):

useEffect(() => {
  // Effect code
  return () => {
    // Cleanup code
  };
}, []);