Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is useRef Hook a must to set and clear intervals in React?

I'm currently understanding the useRef hook and its usage. Accessing the DOM is a pretty straight forward use case which I understood. The second use case is that a ref behaves like an instance field in class components. And the react docs provide an example of setting and clearing a time interval from a click handler. I want to know, if cancelling the time interval from a click handler is not required, can we set and clear intervals with local variables declared within useEffect like below? Or is using a ref as mentioned in the docs always the approach to be taken?

useEffect(() => {
 const id = setInterval(() => {
  // ...
  });
  return () => {
    clearInterval(id);
  };
})
like image 574
Vishwas Avatar asked Jul 06 '19 14:07

Vishwas


People also ask

What is useref in react hook?

Mutable values useRef (initialValue) is a built-in React hook that accepts one argument as the initial value and returns a reference (aka ref ). A reference is an object having a special property current.

How useref () and ReFS (aka references) work in react?

React.useRef () is a hook that creates mutable values persisted between component renderings and references DOM elements. In this post, you’ll learn how useRef () and refs (aka references) work in React. Interesting demos included. 1. Mutable values 2. Access DOM elements 3. Updating references restriction 4. Summary 1. Mutable values

What are hooks in react?

The introduction of hooks a couple of years ago (version 16.8) introduced a massive paradigm shift in the world of React. Hooks allow developers to "hook" into state and component lifecycles without the use of classes! In this post, we're going to look at the useRef hook, how it works, and why we should use it. What is useRef?

How to use setTimeout in React components?

Use setTimeout in your React components to execute a function or block of code after a period of time. Let’s explore how to use setTimeout in React. There is also a similar method called setInterval Show activity on this post.


Video Answer


2 Answers

As stated at the docs you shared;

If we just wanted to set an interval, we wouldn’t need the ref (id could be local to the effect).

  useEffect(() => {
    const id = setInterval(() => {
      setCounter(prev => prev + 1);
    }, 1000);
    return () => {
      clearInterval(id);
    };
  });

but it’s useful if we want to clear the interval from an event handler:

// ...
function handleCancelClick() {
  clearInterval(intervalRef.current);
}
  // ...
like image 95
Dennis Vash Avatar answered Sep 28 '22 05:09

Dennis Vash


I think the example is just for demonstrating how useRef works, though I personal cannot find many use case for useRef except in <input ref={inputEl} /> where inputEl is defined with useRef. For if you want to define something like an component instance variable, why not use useState or useMemo? I want to learn that too actually (Why using useRef in this react example? just for concept demostration?)

As for the react doc example https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables:

function Timer() {
  const intervalRef = useRef();

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    intervalRef.current = id;
    return () => {
      clearInterval(intervalRef.current);
    };
  });

  // ...
  function handleCancelClick() {
    clearInterval(intervalRef.current);
  }
  // ...
}

I tried and can achieve the same without useRef as below:

function Timer() {
  const interval = null;

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    interval = id;
    return () => {
      clearInterval(interval);
    };
  });

  // ...
  function handleCancelClick() {
    clearInterval(interval);
  }
  // ...
}
like image 22
Peter_101 Avatar answered Sep 28 '22 03:09

Peter_101