@cideM/

timer

React

A timer that runs every second and increases value. The amount by which the value is increased can be adjusted by the user. Uses hooks.

fork
loading
Files
  • src
    • App.js
    • App.css
    • App.test.js
    • index.css
    • index.js
    • logo.svg
  • public
  • package.json
src/App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React from "react";
import "./App.css";

function SomeChild({ value }) {
  return <p>Value: {value}</p>;
}

function Input({ onChange, id, type, text }) {
  return (
    <input
      type={type}
      id={id}
      value={text}
      onChange={e => {
        onChange(e.target.value);
      }}
    />
  );
}

function App() {
  const [input, setInput] = React.useState(`1`);
  const [x, setX] = React.useState(0);
  const savedCallback = React.useRef();

  React.useEffect(() => {
    savedCallback.current = () => {
      setX(x + Number(input));
    };
  });

  React.useEffect(() => {
    let id = setInterval(() => {
      savedCallback.current();
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <main className="App">
      <Input id="timer-input" type="text" text={input} onChange={setInput} />
      <label htmlFor="timer-input">Enter a number:</label>
      <SomeChild value={x} />
    </main>
  );
}

export default App;