꾸매코딩

[React] new Date(), state를 활용한 동적인 현재시간 나타내기 본문

Project/Timer Project

[React] new Date(), state를 활용한 동적인 현재시간 나타내기

꾸매코더 2021. 7. 6. 17:50
반응형


오류

import React, { useState } from 'react'

export default function App() {
  const [timer, setTimer] = useState('0');

  const currentTimer = () => {
    const date = new Date();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    return (`${hours}:${minutes}:${seconds}`)
  }
  const currentTime = currentTimer()
  setTimer(currentTime)
  return (
    <>
      <span>{timer}</span>
    </>
  )
}

처음 작성했던 코드인데 오류가 발생했다.

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
에러: 재 렌더링이 너무 많다. React는 무한루프를 막기위해 렌더링 횟수를 제한한다. 

해결

return이 아닌 함수 내에서 바로 state에 저장을 해주었더니 오류가 사라졌다.

import React, { useState } from 'react'

export default function App() {
  const [timer, setTimer] = useState("00:00:00");

  const currentTimer = () => {
    const date = new Date();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    setTimer(`${hours}:${minutes}:${seconds}`)
  }

  const startTimer = () => {
    setInterval(currentTimer, 1000)
  }

  startTimer()

  return (
    <>
      <h1>{timer}</h1>
    </>
  )
}

느낀점

아직 React 사용이 익숙하지 못한것 같다. 역시 직접 해봐야 느낄수 있는것 같다.

내가 잘 알지 못하는 내용에 부딪히면서 꾸준히 공부해야겠다고 생각하게 되었다.

반응형