React Hooks Example: Timer

Simple React Hooks example. A timer that pauses when you hold the mouse button. Creates and uses a custom Hook.

by Arthur Lutkevichus

HTML

<div id="app"></div>

CSS

div {
  padding: 20px;
}

React

function useStateCallback(initialValue) {
    const [state, setState] = React.useState(initialValue);
    const stateCallback = React.useRef(null);
    
    const setStateWithCallback = (newState, callback) => {
        stateCallback.current = callback;
        setState(newState);
    };

    React.useEffect(() => {
        if (stateCallback.current instanceof Function) {
            stateCallback.current();
            stateCallback.current = null;
        }
    }, [state]);

    return [state, setStateWithCallback];
};

function ClickTimes () {
  const [times, setTimes] = useStateCallback(0);
  const [remainder, setRemainder] = React.useState();

  return (
    <div>
      <button onClick={() => setTimes(prevState => prevState + 1, () => setRemainder(times % 2))}>Clicked {times}</button>
      <code>{remainder}</code>
    </div>
  )
}

ReactDOM.render(<ClickTimes />, document.querySelector("#app"))