React hooks counter

    0

    0

    maidangzhu

    The code creates a function called Counter with two properties, count and setCount. The function saves a callback function as savedCallback. The function Counter calls the callback function every 1000 milliseconds using an effect. The function Tick calls the callback function and saves the current value of savedCallback. The code returns the HTML title for the Counter.

    Library: react

    import React, { useState, useRef, useEffect } from "react";
    
    function Counter() {
      const [count, setCount] = useState(0);
      const savedCallback = useRef();
    
      function callback() {
        setCount(count + 1);
      }
    
      useEffect(() => {
        savedCallback.current = callback;
      });
    
      useEffect(() => {
        function tick() {
          savedCallback.current();
        }
    
        let id = setInterval(tick, 1000);
        return () => clearInterval(id);
      }, []);
    
      return <h1>{count}</h1>;
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.