⚡️etc.

[원티드] 프리온보딩 프론트엔드 챌린지 2차 세션 실습

s2ylvia 2024. 6. 8. 22:03
import React, { useEffect, useRef, useReducer, createContext } from 'react'

function reducer(state, action){
  switch(action.type){
    case 'up': return state + 1
    case 'down' : return state - 1
    default: throw new Error()
  }
}

//props말고도 상태를 전역적으로 사용할 수 있게 해주는..
const CounterContext = createContext();

const App = () => {
  const [count, dispatch] = useReducer(reducer, 0)
  //렌더링에 필요하지않는 값을 참조할 수 있는 hook
  const countRef = useRef(0)

  useEffect(() => {
    //3초동안 count 값이 변하면 그 값을 가져올 수 있다
    countRef.current = count;
  }, [count])

  return (
    //컴포넌트간에 공유하고자 하는 값을 value 라는 Props로 설정하면 
    //자식 컴포넌트들에서 해당 값에 바로 접근을 할 수 있다.
    <CounterContext.Provider value={{reducer}}>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({type: 'up'})}>up</button>
      <button onClick={() => dispatch({type: 'down'})}>down</button>
      <button onClick={() => {
        setTimeout(() => alert(countRef.current), 3000)
      }}>alert count after 3 seconds</button>
    </CounterContext.Provider>
  )
}

export default App

 

 

React의 다양한 hook들을 사용해 만들어본 카운터이다.

거의 개발할 때는 useState나 useEffect만 사용해봤는데 추가적으로 학습할 수 있어서 뜻깊었다.