React Basic Hooks - useEffects sample

by ahmdilloo

HTML

<div id="root"></div>
<div id="other-div"></div>

CSS

body {
  height: 100vh;
  font-family: 'Open Sans', sans-serif;
  font-weight: bold;
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-content: center;
  flex-wrap: wrap;
  text-align: center
}

#root, #other-div {
  width: 100%;
}

React

const {useState, useEffect, useCallback} = React;

const animationSpeed = 7

const useCounter = (ending, start) => {
  const [count, setCount] = useState(0)
  const ratio = parseInt(ending/100)
  useEffect(() => {
  		if (start) {
      	const interval = setInterval(() => {
        if (count < ending) {
          setCount(count+ratio > ending ? ending : count+ratio)
        } else {
        	clearInterval(interval)
        }
        }, animationSpeed)
        return  () => clearInterval(interval)
      }
  }, [count, start])
  return count
}

const AnimationNumber = ({ number , start}) => {
  let count = useCounter(number, start)
  return (
    <div
      data-target={number}
    >
      <strong>
        <span>{count}</span>
      </strong>
      
    </div>
  );
};

function Example() {
	const [starter, setStarter] = useState(false)
	const start = useCallback(() => {
  	setStarter(true)
  }, [])
  return (
    <div>
      <button onClick={start}>Start!</button>
      <AnimationNumber number={100} start={starter} />
      <AnimationNumber number={1500} start={starter} />
      <AnimationNumber number={5000} start={starter} />
      <AnimationNumber number={590} start={starter} />
      <AnimationNumber number={1024} start={starter} />
      <AnimationNumber number={3600} start={starter} />
    </div>
  );
}

ReactDOM.render( <Example />, document.getElementById('root') );