React useTimeout Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to implement the setTimeout() function in a declarative manner using the useTimeout custom hook in React. This hook allows us to set up a timeout and clean it up easily, while also remembering the latest callback function. We will also see an example of using the useTimeout hook to create a one-second timer that updates the state of a component every second.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38411{{"`React useTimeout Hook`"}} react/hooks -.-> lab-38411{{"`React useTimeout Hook`"}} react/use_state_reducer -.-> lab-38411{{"`React useTimeout Hook`"}} end

React useTimeout Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To implement setTimeout() in a declarative manner, create a custom hook that takes a callback and a delay. Use the useRef() hook to create a ref for the callback function, and use the useEffect() hook to remember the latest callback. Then, use the useEffect() hook to set up the timeout and clean up.

Here is an example code snippet that demonstrates this approach:

const useTimeout = (callback, delay) => {
  const savedCallback = React.useRef();

  React.useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  React.useEffect(() => {
    const tick = () => {
      savedCallback.current();
    };
    if (delay !== null) {
      let id = setTimeout(tick, delay);
      return () => clearTimeout(id);
    }
  }, [delay]);
};

const OneSecondTimer = (props) => {
  const [seconds, setSeconds] = React.useState(0);

  useTimeout(() => {
    setSeconds(seconds + 1);
  }, 1000);

  return <p>{seconds}</p>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<OneSecondTimer />);

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 useTimeout Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like