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만 사용해봤는데 추가적으로 학습할 수 있어서 뜻깊었다.
'⚡️etc.' 카테고리의 다른 글
[GitHub Pages] gh-pages 라이브러리를 활용하여 배포하기 (0) | 2024.09.02 |
---|---|
Axios와 Promise에 대해 알아보자 (0) | 2024.06.19 |
[JavaScript] var, let, const의 차이에 대해 알아보자(scope, hoisting...) (0) | 2024.06.19 |
[원티드] 프리온보딩 프론트엔드 챌린지 3차 세션 실습 (1) | 2024.06.13 |
[Next.js X GitHub] Next.js 앱을 Github에 연동하기 (0) | 2024.04.16 |