Introduction
In this lab, we will learn how to use the useEffectOnce hook in React to run a callback function at most once when a certain condition becomes true. This can be useful for situations where we want to execute a specific action only once, such as when a component mounts or when a button is clicked. By the end of this lab, you will have a better understanding of how to implement this hook in your React applications.
React useEffectOnce Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
The code below implements a function useEffectOnce(callback, when) that runs a callback only once when a when condition becomes true.
To implement this function:
- Create a variable
hasRunOnceusing theuseRef()hook to keep track of the execution status of the effect. - Use the
useEffect()hook that runs only when thewhencondition changes. - Inside the
useEffect()hook, check ifwhenistrueand the effect has not executed before. If both aretrue, runcallbackand sethasRunOncetotrue.
const useEffectOnce = (callback, when) => {
const hasRunOnce = React.useRef(false);
React.useEffect(() => {
if (when && !hasRunOnce.current) {
callback();
hasRunOnce.current = true;
}
}, [when]);
};
Here's an example usage of useEffectOnce():
const App = () => {
const [clicked, setClicked] = React.useState(false);
useEffectOnce(() => {
console.log("mounted");
}, clicked);
return <button => setClicked(true)}>Click me</button>;
};
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
In the example, useEffectOnce() is used to log "mounted" to the console when the button is clicked for the first time. The useEffectOnce() hook is passed two arguments: the callback to run and the when condition to check. The when condition is set to the clicked state, so the callback runs only when clicked is true for the first time.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useEffectOnce Hook lab. You can practice more labs in LabEx to improve your skills.