automated counter with react hooks code example

Example 1: counter with react hooks

import React, { useState } from 'react';

function Example() {
  // Declaración de una variable de estado que llamaremos "count"  const [count, setCount] = useState(0);
  return (
    

You clicked {count} times

); }

Example 2: automated counter with react hooks

const { useState, useEffect, useRef } = React;

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    let id = setInterval(() => {
      savedCallback.current();
    }, delay);
    return () => clearInterval(id);
  }, [delay]);
}

function App() {
  const [counter, setCounter] = useState(0);

  useInterval(() => {
    setCounter(counter + 1);
  }, 1000);

  return 

{counter}

; }; ReactDOM.render( , document.getElementById('root') );

Tags:

Misc Example