ReactuseEffect
Hooks 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 codeuseEffect
The 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
prevDepsAry
Used to record the dependency array when it was last rendered.effectIndex
Used to indicate the location of the side effects of the current treatment.
Next isuseEffect
Function 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++; }
useEffect
The implementation logic is:
- Verify incoming
callback
Whether it is a function. If not, an error is thrown. - If not passed in
depsAry
, then it is executed every time the component renderscallback
。 - If it is passed
depsAry
, 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
。 - renew
prevDepsAry
The corresponding item of , is used as a comparison the next time the component is rendered. -
effectIndex
Increase by itself to ensure the next oneuseEffect
The processing uses the correct index.
The next step is definedrender
function:
function render() { // Reset side effects index effectIndex = 0; // Use ReactDOM to render App components (<App />, ('root')); }
Before each rendering,effectIndex
Must be reset to 0, which guaranteesuseEffect
Correctness 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 ituseEffect
The problem. Of course, the actual ReactuseEffect
The 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!