SoFunction
Updated on 2025-04-07

Detailed explanation of the code simple implementation of useEffect principle in React

ReactuseEffectHooks are an important tool in React function components to handle side effects (such as API requests, subscriptions, or manual modification of DOM, etc.). In this article, a simple example will be explained in the codeuseEffectThe basic principle of

First, two global variables are defined to track different side effect states:

let prevDepsAry = []; // Store the last value of the dependency arraylet effectIndex = 0; // Current side effects index

prevDepsAryUsed to record the dependency array when it was last rendered.effectIndexUsed to indicate the location of the side effects of the current treatment.

Next isuseEffectFunction implementation:

function useEffect(callback, depsAry) {
  // Check whether callback is a function  if ((callback) !== '[object Function]') {
    throw new Error('The first parameter of useEffect must be a function');
  }

  // If the dependency array is not provided, callback is executed by default every rendering  if (typeof depsAry === 'undefined') {
    callback();
  } else {
    // Verify whether depsAry is an array    if ((depsAry) !== '[object Array]') {
      throw new Error('The second parameter of useEffect must be an array');
    }

    // Get the previous value of the dependency array    let prevDeps = prevDepsAry[effectIndex];

    // Compare each value of the dependency array to determine if there has been any change    let hasChanged = prevDeps ? !((dep, index) => dep === prevDeps[index]) : true;

    // If the dependency changes or is rendered for the first time (hasChanged is true), execute callback    if (hasChanged) {
      callback();
    }

    // Store the current dependency array for comparison during next rendering    prevDepsAry[effectIndex] = depsAry;
  }

  // Add side effects index and prepare for the next side effect  effectIndex++;
}

useEffectThe implementation logic is:

  • Verify incomingcallbackWhether it is a function. If not, an error is thrown.
  • If not passed indepsAry, then it is executed every time the component renderscallback
  • If it is passeddepsAry, first verify that it is an array. Then, get the last dependency array and compare item by item with the current array. If there is a difference or is rendering for the first time, then executecallback
  • renewprevDepsAryThe corresponding item of , is used as a comparison the next time the component is rendered.
  • effectIndexIncrease by itself to ensure the next oneuseEffectThe processing uses the correct index.

The next step is definedrenderfunction:

function render() {
  // Reset side effects index  effectIndex = 0;
  // Use ReactDOM to render App components  (<App />, ('root'));
}

Before each rendering,effectIndexMust be reset to 0, which guaranteesuseEffectCorrectness when dealing with dependencies.

Finally, use it in the App componentuseEffect

function App() {
  // Use custom useState and useEffect
  useEffect(() => {
    ('Side effect function has been executed');
    // Here, operations with side effects such as API requests, subscription events, etc. may be performed    // When the dependency changes, the code here will be executed  }, [/* Dependency array */]);

  return (
    // Component JSX structure    <div></div>
  );
}

Called in the componentuseEffect, and pass a function that performs side effect operations and a dependency array, implementing the requirement of executing side effect logic when dependencies change.

The last step is to callrender()to trigger the first rendering.

Through the above code, I answered single-handedly how to implement ituseEffectThe problem. Of course, the actual ReactuseEffectThe implementation is more complex and involves scheduling and cleaning operations, but the above code provides a good starting point for understanding its fundamentals.

This is the end of this article about the simple implementation of the code of useEffect in React. For more related React useEffect content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!