Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react clearinterval outside of useefect

/*
If you need to save variables across re-renders use useRef which in this case acts
like a class instance field, also note that mutations to refs does not trigger a
re-render.

This will give you the ability to clear the interval from outside of useEffect
*/

function Child(props) {
  let [timerCount, setTimer] = useState(0)
  const intervalRef = useRef(null)

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimer(prevState => prevState + 1)
    }, 1000)

    return () => clearInterval(intervalRef.current)
  }, [])

  function clearTimer() {
    clearInterval(intervalRef.current)
    intervalRef.current = null
  }

  return (
    <div>
      <div>Timer {timerCount}</div>
      <button onClick={clearTimer}>ClearTimer</button>
    </div>
  )
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: ajax:drop-down remove an d add select option 
Javascript :: reduce() method executes a reducer function on each element of the array and returns a single output value. 
Javascript :: javascript array keyshort 
Javascript :: unique elements 
Javascript :: A Note about Floats 
Javascript :: vuejs jitsi 
Javascript :: iteration methods 
Javascript :: regular expression for twitter embedded tweets 
Javascript :: close worker 
Javascript :: Learning Arrow function Syntax 
Javascript :: javascript loob array 
Javascript :: loop through async javascript -5 
Javascript :: space station json file 
Javascript :: convert base64 to image javascript 
Javascript :: preventdefault called two times 
Javascript :: does script defer keep order 
Javascript :: 24 hour datepicker 
Javascript :: Uploading profile pic with react.js node.js express.js REST API to sqlite DB 
Javascript :: customize bar in chartjs 
Javascript :: sequelize default curdate 
Javascript :: full calendar change default view 
Javascript :: intialize vue select using cdn 
Javascript :: cypher neo4j 
Javascript :: rxjs fromevent mouseover 
Javascript :: a complex label expression before a colon must be parenthesized 
Javascript :: sending string from jquery ajax to asp.net mvc controller. 
Javascript :: value.js package 
Javascript :: variables are used to store data values. 
Javascript :: enzyme to json 
Javascript :: Remove adjacent number 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =