import { useCallback } from 'react'
const memoizedCallback = useCallback(() => {
// 상태가 변경이 되었을 때 반환할 callback 함수
doSomething(state, state2)
}, [state, state2])
주의할 점
const memoizedCallback = useCallback(() => {
// 상태가 변경이 되었을 때 반환할 callback 함수
doSomething()
}, [])
import { useMemo } from 'react'
const memoizedValue = useMemo(() => doSomething(state1, state2), [state1, state2])
import { memo } from 'react'
const Component = memo((props) => {
return <>{props.something}</>
})
import { createContext, useContext, useState } from 'react'
const Global = createContext()
const Welcome = () => {
const obj = useContext(Global)
return (
<div>
Welecome {obj.nickname}
</div>
)
}
export const MyApp = () => {
const [nickname, setNickname] = useState('cloudcoke')
const Users = {
nickname
}
return (
<Global.Provider value={Users}>
<Welcome />
</Global.Provider>
)
}
import { useReducer } from 'react'
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return {count: state.count + 1}
case 'decrement':
return {count: state.count - 1}
default:
throw new Error()
}
}
const Counter = () => {
const initialState = {count: 0}
const [state, dispatch] = useReducer(reducer, initialState)
const increment = () => {
dispatch({type: 'increment'})
}
const decrement = () => {
dispatch({type: 'decrement'})
}
return (
<>
Count : {state.count}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</>
)
}
// useState
const [state1, setState1] = useState(init1)
const [state2, setState2] = useState(init2)
const [state3, setState3] = useState(init3)
...
// useReducer
const initialState = {
init1,
init2,
init3,
...
}
const [state, dispatch] = useReducer(reducer, initialState)
const initialState = {count: 0}
const [state, dispatch] = useReducer(reducer, initialState)
const reducer = (state, action) => {
...
}
React 공식 문서 - Hooks API Reference
React Docs BETA
React 공식 문서 - React.memo