Teachnique
      CourseRoadmaps
      Login

      useStateuseEffectuseLayoutEffectuseReduceruseRefforwardRefuseContextClosure Trap in Hooks

      Feedback

      Submit request if you have any questions.

      Course
      useEffect

      React Mastery Guide

      Unlock the full potential of React with our comprehensive guide. From basics to advanced techniques, this course covers everything you need to build dynamic, high-performance web applications. Perfect for developers at any level, start mastering React today!

      useEffect


      
      useEffect is a Hook in React that allows you to perform side effects in function components.
      
      Previously, function components were:
      Pure functions: given the same inputs, always return the same outputs and do not produce any observable side effects.
      function add(x, y) {
      return x + y;
      }
      
      Side effects include modifying external variables, making network requests, manipulating the DOM, etc. Here is an example of a function with side effects:
      javascriptCopy codelet count = 0; // External variable
      
      function incrementCount() {
      count += 1; // Modifies an external variable
      console.log(count); // Printing to the console, also a side effect
      }
      This incrementCount function modifies the external variable count and prints information to the console. These operations make the function unpredictable and non-independent because its behavior depends not only on its input but also on the state of the external count variable, and it affects other parts of the system by printing to the console.
      
      Let's write App.tsx:
      
      Note that if you want to use async/await syntax, you need to write a separate function because the function passed to useEffect does not support async.
      
      When you visit the browser, you'll see that after 2 seconds, the state changes to 666:
      
      
      Asynchronous logic such as fetching data or timers should be placed inside useEffect.
      
      Now, let's take a closer look at useEffect:
      useEffect(() => {
      queryData().then((data) => {
      setNum(data);
      });
      }, []);
      Why do we pass an empty array as the second argument?
      
      This array is called the dependency array. React uses it to determine whether to re-run the effect function. If it's not passed, the effect function will execute on every render.
      
      Let's add a console log:
      useEffect(() => {
      console.log('This is a log..');
      queryData().then((data) => {
      setNum(data);
      });
      }, []);
      Now, this component will render twice: once initially and then again 2 seconds later when setNum triggers a re-render, causing the function to execute twice.
      
      Open the devtools and you’ll see:
      
      The effect function only runs ONCE because [] remains unchanged between renders.
      
      You can also use any constant values in the array [], as they won't change and will not trigger re-execution of the effect:
      useEffect(() => {
      console.log('This is a log..');
      queryData().then((data) => {
      setNum(data);
      });
      }, [1, 2, 3, ‘xxx’]);
      However, if one of the values changes, it will trigger re-execution of the effect:
      useEffect(() => {
      console.log('This is a log..');
      queryData().then((data) => {
      setNum(data);
      });
      }, [1, 2, 3, 'xxx', Date.now()]);
      
      
      Now you can see that the useEffect runs twice:
      • Execution on Initial Mount
      • Re-execution Due to Date.now(): Because Date.now() is included in the dependency array, it produces a new timestamp with each render, causing the dependency array of the useEffect to detect a change. As a result, the useEffect runs again.