useEffect hook

https://react.dev/reference/react/useEffect

useEffect hook

useEffect is a React Hook that lets you synchronize a component with an external system.

useEffect is a hook in React that allows you to perform side effects in function components.

There is no need for urban dictionary - basically any work outside of the component.

Some examples of side effects are:

  1. subscriptions,
  2. fetching data,
  3. directly updating the DOM,
  4. event listeners,
  5. timers, etc.

Details

// Why are we passing an empty array as the second argument?
// If the dependency array is empty [], useEffect runs only on initial render.
// If we remove the second argument, useEffect runs on re-renders too.
useEffect(() => {
    console.log('hello from useEffect');
}, []);
  1. accepts two arguments (second optional)
  2. first argument - callback function
  3. second argument - dependency array
  4. by default, it runs on each render (initial and re-render)
  5. callback can’t return promise (so can’t make it async)
    1. This is ok because the callback function is using an async function
      useEffect(() => {
          const someFunc = () => {
              await fetch
          }
          someFunc();
      }, []);
      
    2. But the callback function itself cannot be async. This is not ok.
      useEffect(async () => {
          someFunc();
      }, []);
      

Sample implementations

https://github.com/explorer436/programming-playground/tree/main/react-playground


Links to this note