프로그래밍
useCallback 사용 예시
iIxmont
2021. 9. 20. 16:40
페이지 컴포넌트에서는 아래와 같이 작성한다
export function SomePage() {
const { closeSomething } = useSomething()
const { pathname } = useLocation()
const onClickButton = useCallback(() => {
closeSomething(pathname)
},[pathname, closeSomething])
return (
<button onClick={onClickButton}>this button</button>
)
}
1. 버튼의 onClick 함수를 useCallback 으로 정의한다
2. useCallback 의 [ 파라미터 ] 부분에는 useCallback 안에서 사용했던 변수와 함수를 작성한다.
export function useSomething() {
const closeSomething = React.useCallback(() => {
}, [함수에서 사용하는 변수, 함수])
return { closeSomething }
}
useSomething 훅에서도 같은 형태로 useCallback 으로 정의한다.
그리고 함수를 return { closeSomething }한다