30秒学会 React 片段 · 2023年6月18日

30秒学会 React 片段 – React useEffectOnce hook

Runs a callback at most once when a condition becomes true.

  • Use the useRef() hook to create a variable, hasRunOnce, to keep track of the execution status of the effect.
  • Use the useEffect() that runs only when the when condition changes.
  • Check if when is true and the effect has not executed before. If both are true, run callback and set hasRunOnce to true.

代码实现

const useEffectOnce = (callback, when) => {
  const hasRunOnce = React.useRef(false);
  React.useEffect(() => {
    if (when && !hasRunOnce.current) {
      callback();
      hasRunOnce.current = true;
    }
  }, [when]);
};

使用样例

const App = () => {
  const [clicked, setClicked] = React.useState(false);
  useEffectOnce(() => {
    console.log('mounted');
  }, clicked);
  return <button onClick={() => setClicked(true)}>Click me</button>;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
);

翻译自:https://www.30secondsofcode.org/react/s/use-effect-once