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.
以上是如何最佳化 useEffect Hook 以僅在初始渲染時觸發函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!