- Published on
React Hooks Api (2)
- Author
- Name
- yceffort
useReducer
const [state, dispatch] = useReducer(reducer, initialArg, init)
useState
์ ๋์ฒด ํจ์๋ค. ๋ค์์ ํ์ ๊ฐ์ ๋ง๋๋ ๋ณต์กํ ๋ก์ง, ํน์ ๋ค์ state๊ฐ ์ด์ state์ ์์กด์ ์ธ ๊ฒฝ์ฐ์ ์ด๋ค. ๋ญ๊ฐ ๋ญ์ง ๋ชจ๋ฅด๊ฒ ์ผ๋๊น ์์ ๋ฅผ ๋ณด์.
useState๋ฅผ ์ฐ๊ธฐ์
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount)
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button>
<button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button>
</>
)
}
const initialState = {count: 0}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1}
case 'decrement':
return {count: state.count - 1}
default:
throw new Error()
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
)
}
function init(initialCount) {
return {count: initialCount}
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1}
case 'decrement':
return {count: state.count - 1}
case 'reset':
return init(action.payload)
default:
throw new Error()
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
)
}
์์ ๋ฅผ ๋ณด๋ ๋์ถฉ ๊ฐ์ด ์จ๋ค. dispatch๋ฅผ ํตํด์ state๊ฐ์ ๋ณํ๋ฅผ ์ฃผ์ง ์๊ณ state๊ฐ ๋ณํ์ ํธ๋ฆฌ๊ฑฐ๋ฅผ ์ค ์ ์๊ณ , ์ด ํธ๋ฆฌ๊ฑฐ๋ฅผ ์ด์ฉํด ์ฌ๋ฌ๊ฐ์ state์ ๋ณํ๋ฅผ ์ค ์๋ ์๋ค.
useCallback
๋ฉ๋ชจ์ด์ ์ด์ ๋ ์ฝ๋ฐฑ์ ๋ฐํํ๋ค.
const memoizedCallback = useCallback(() => {
doSomething(a, b)
}, [a, b])
๋์ผํ ์ฝ๋ฐฑ์ ๋ฐ๋ผ๋ด์ผํ๋ ์์ ์ปดํฌ๋ํธ์๊ฒ ์ฌ์ฉํ ๋ ์ ์ฉํ๋ค.
useMemo
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])
๋ฉ๋ชจ์ด์ ์ด์
๋ ๊ฐ์ ๋ฐํํ๋ค. useMemo
๋ ์์กด์ฑ์ด ๋ณ๊ฒฝ๋์์ ๋๋ง, ๋ฉ๋ชจ์ ์ด์
๋ ๊ฐ์ ๋ค์ ๊ณ์ฐํ ๊ฒ์ด๋ค.
useRef
const refContainer = useRef(initialValue)
function TextInputWithFocusButton() {
const inputEl = useRef(null)
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus()
}
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
)
}
useRef
๋ .current
์ ๋ณ๊ฒฝ๊ฐ๋ฅํ ref๊ฐ์ ๋ด์ ์ ์๋ค. ๋ถ๋ชจ ํด๋์ค์์ ํน์ dom๊ฐ์ฒด๋ฅผ ๊ณ์ ์ถ์ ํด์ผํ ๋ ์ ์ฉํ๋ค. ๋ค๋ง .current
๋ฅผ ๋ณ๊ฒฝํ๋ค๊ณ ํด์ ๋ฆฌ๋ ๋๋ง์ด ์ผ์ด๋์ง๋ ์๋๋ค.