React/Practice

UseEffect, Props를 사용한 시계만들기 with Example code

3.dev 2023. 1. 27. 14:50
반응형

(실습 난이도 : 하, 소요시간 : 20min±)
이번엔 useEffect Hook과 props기능을 사용해서 만들수 있는 기초적인 시계를 만들어보자.

먼저 App.js에서 기본적으로 버튼과 그 버튼으로 켜지고 꺼질 수 있는 시계기능을 코딩해보자.

App.js

import React,{useState} from 'react';
import Time from './components/Time'

function App() {
  const [showTime,setShowTime] = useState(false);

  return <div>
    {showTime && <Time showTime={showTime}/>}
    <button onClick={()=>{setShowTime(!showTime)}}>Time Toggle</button>
  </div>
}

export default App;

가장 먼저 button을 생성하고 useState를 사용해서 버튼을 누를 때마다 false <=> true 값을 바꿔주는 기능을 넣었다.
그리고 이 showTime이라는 상태값이 true일때만 사용할 수 있도록
and연산자를 사용해서

{showTime && <Time showTime={showTime}/>}

showTime의 상태가 true일때만 Time.js가 활성화 될 수 있도록 했다.
그럼 이제 Time.js Component를 만들고 코딩해보자.

Time.js

import React,{useEffect, useState} from "react";

export default function Time () {

  const [clock, setClock] = useState("00시00분00초");

  useEffect(()=> {
    
    const Timer = setInterval(() => {
      let time = new Date();
      setClock(time.getHours()+"시"+time.getMinutes()+"분"+time.getSeconds()+"초");
    },1000);
    console.log("mount!");
    
    return ()=>{
       clearInterval(Timer);
       console.log("unmount!")
    }

  },[]);

  return <div>
    <p>{clock}</p>
    <p>Time Mount Success!</p>
  </div>
};

한줄한줄 다시 살펴보자.
먼저 useState를 이용해서 clock이라는 변수를 만들고 자연스럽게 로딩하기위해 00시00분00초를 기본값으로 설정하자.

  const [clock, setClock] = useState("00시00분00초");

useEffect를 사용해서 Time.js가 mount될 경우에만
new Date()로 현재시각을 가져와 clock에 시,분,초를 1초마다 바꿔줄수 있도록 작성했다.

그리고 Time.js가 mount될 때마다 "mount!"를 콘솔에 표시하도록 했다.
또 반대로 unmount될때는 "unmount!"를 콘솔에 표시하도록 했다.

  useEffect(()=> {
    
    const Timer = setInterval(() => {
      let time = new Date();
      setClock(time.getHours()+"시"+time.getMinutes()+"분"+time.getSeconds()+"초");
    },1000);
    console.log("mount!");
    
    return ()=>{
       clearInterval(Timer);
       console.log("unmount!")
    }

  },[]);

이제 clock에는 시,분,초가 정상적으로 담겨있을 것이다.
이 값을 리턴해보자.

  return <div>
    <p>{clock}</p>
    <p>Time Mount Success!</p>
  </div>


mount했을 때, unmount했을 때 모두 console에서 알려주며
시간 또한 정확한 현재 시간을 가져온다.

이대로 끝나기엔 너무 아쉬우니 날짜도 가져와보자.
똑같이 "day"라는 state변수를 만들어주자.

  const [day, setDay] = useState("0000년00월00일");

이제 day의 값을 설정하고 바꿔주어야하는데
날짜는 1초마다 값을 바꿀필요가 없기 때문에 setInterval을 사용하지 않고
props를 사용해서 Time.js가 mount되었을때 값을 지정해 줄 수 있도록 하자.
앞서 App.js에서 Time.js를 가져왔던 부분에 showTime 상태를 넘겨준다.

App.js

{showTime && <Time showTime={showTime}/>}

이제 Time.js에서 props로 받고 활용하면 된다.
가장 앞줄 Time함수에서 ( )괄호 안에 props를 입력했다.

Time.js

export default function Time (props) {

useEffect에서 props.showTime의 값이 바뀔때만 동작하도록 했다.
연,월,일을 가져오고 월을 0월부터 시작하기 때문에 +1값을 넣어줬다.
또, 날짜가 설정될땐 console에서 확인할 수 있게 작성했다.

Time.js

  useEffect(()=>{
      let time = new Date();
      setDay(time.getFullYear()+"년"+(time.getMonth()+1)+"월"+time.getDate()+"일");
      console.log("날짜가 설정되었습니다.")
  },[props.showTime])

이제 이 값들을 리턴해보자.
day상태값만 추가하면 된다.

Time.js

  return <div>
    <p>{day}</p>
    <p>{clock}</p>
    <p>Time Mount Success!</p>
  </div>

이제 결과물을 보자.

정상적으로 mount했을때만 연,월,일을 변경하고 시,분,초는 1초마다 변경된다.

최종코드 App.js

import React,{useState} from 'react';
import Time from './components/Time'

function App() {
  const [showTime,setShowTime] = useState(false);

  return <div>
    {showTime && <Time showTime={showTime}/>}
    <button onClick={()=>{setShowTime(!showTime)}}>Time Toggle</button>
  </div>
}

export default App;

최종코드 Time.js

import React,{useEffect, useState} from "react";

export default function Time (props) {

  const [clock, setClock] = useState("00시00분00초");
  const [day, setDay] = useState("0000년00월00일");
  
  useEffect(()=>{
      let time = new Date();
      setDay(time.getFullYear()+"년"+(time.getMonth()+1)+"월"+time.getDate()+"일");
      console.log("날짜가 설정되었습니다.")
  },[props.showTime])

  useEffect(()=> {
    const Timer = setInterval(() => {
      let time = new Date();
      setClock(time.getHours()+"시"+time.getMinutes()+"분"+time.getSeconds()+"초");
    },1000);
    console.log("mount!");
    return ()=>{
       clearInterval(Timer);
       console.log("unmount!")
    }

  },[]);

  return <div>
    <p>{day}</p>
    <p>{clock}</p>
    <p>Time Mount Success!</p>
  </div>
};
반응형