첫번째 인자는 메모이제이션 할 콜백함수, 두번째 인자는 의존성 배열을 받음
useCallback(()=> {
return value;
},[item])
원하는 요소의 리랜더링을 방지할 수 있다
import { useCallback } from 'react';
function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
메모화된 콜백에서 상태 업데이트
function TodoList() {
const [todos, setTodos] = useState([]);
const handleAddTodo = useCallback((text) => {
const newTodo = { id: nextId++, text };
setTodos(todos => [...todos, newTodo]);
}, []);
Effect가 너무 자주 발생하지 않도록 방지
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const createOptions = useCallback(() => {
return {
serverUrl: 'https://localhost:1234',
roomId: roomId
};
}, [roomId]); // ✅ Only changes when roomId changes
useEffect(() => {
const options = createOptions();
const connection = createConnection();
connection.connect();
return () => connection.disconnect();
}, [createOptions]); // ✅ Only changes when createOptions changes
// ...
custom hook 최적화
import { useState, useCallback, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const useModal = () => {
const [modal, setModal] = useState(false);
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
const openModal = useCallback(() => {
setModal(true);
}, []);
const closeModal = useCallback(() => {
setModal(false);
}, []);
const closeModalIfClickOutside = useCallback(
(e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
if (e.target === e.currentTarget) {
closeModal();
}
},
[],
);
const disableScroll = () => {
window.onscroll = () => {
window.scrollTo(scrollLeft, scrollTop);
};
};
const enableScroll = () => {
window.onscroll = () => {};
};
useEffect(() => {
if (modal) {
disableScroll();
}
if (!modal) {
enableScroll();
}
}, [modal]);
useEffect(() => {
return () => {
enableScroll();
};
}, []);
return [modal, openModal, closeModal, closeModalIfClickOutside] as const;
};
export default useModal;