React useInterval Hook

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will learn how to implement the setInterval() function in a declarative way using the useInterval custom hook in React. This hook helps us to set up intervals for performing tasks repeatedly at a specified time interval. By the end of this lab, you will have a better understanding of how to use the useInterval hook to create timers, animations, and other time-based features in your React applications.


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-38390{{"`React useInterval Hook`"}} react/hooks -.-> lab-38390{{"`React useInterval Hook`"}} react/use_state_reducer -.-> lab-38390{{"`React useInterval Hook`"}} end

React useInterval 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 setInterval() in a declarative manner, you can create a custom hook that takes a callback and a delay. The first step is to use the useRef() hook to create a ref for the callback function. Then, use a useEffect() hook to remember the latest callback whenever it changes. Finally, use a useEffect() hook dependent on delay to set up the interval and clean up.

Here's an example code snippet for the custom hook:

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

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

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

You can then use this custom hook in your components. For example, to create a timer that updates every second:

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

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

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

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

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

Other React Tutorials you may like