Home >Web Front-end >JS Tutorial >How to Optimize useEffect Hook to Trigger a Function Only on Initial Render?
React's useEffect hook allows for running custom functions in response to changes in the component's props or state. However, in certain scenarios, it's desired to call a function on initial render only, simulating the behavior of the legacy componentDidMount lifecycle method.
Consider the following class-based component:
<code class="javascript">class MyComponent extends React.PureComponent { componentDidMount() { loadDataOnlyOnce(); } render() { ... } }</code>
In a function-based component using hooks, this can be translated as follows:
<code class="javascript">function MyComponent() { useEffect(() => { loadDataOnlyOnce(); // This will fire on every change }, [...???]); return (...); }</code>
To ensure that the function is called only once, an empty array should be provided as the second argument to useEffect:
<code class="javascript">function MyComponent() { useEffect(() => { loadDataOnlyOnce(); }, []); return <div> {/* ... */} </div>; }</code>
By providing an empty array, useEffect will fire only after the initial render phase, allowing for efficient initialization of components without unnecessary rerenders.
The above is the detailed content of How to Optimize useEffect Hook to Trigger a Function Only on Initial Render?. For more information, please follow other related articles on the PHP Chinese website!