useCallback
react에서 컴포넌트가 리렌더링되면 함수들이 새로 다시 만들어집니다. 함수를 선언하고 하는 것은 리소스를 많이 차지하지는 않지만
최적화를 위해서는 props가 바뀌지 않을때 Virtual DOM 에 새로 렌더링을 하지 않고 컴포넌트의 결과물을 재사용하는 부분도 중요합니다.
useCallback 사용법
- Input 값 추적하기
Input.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useCallback } from "react"; | |
const Input = () => { | |
const [value, setValue] = useState('') | |
const onChange = useCallback(e => { | |
setValue(e.target.value) | |
} | |
) | |
return ( | |
<> | |
<input onChange={onChange}/> | |
<p>{value}</p> | |
</> | |
) | |
} | |
export default Input; |
Input으로 입력받은 값이 변할때마다 컴포넌트는 리렌더링되는데 이럴때마다 함수가 재 선언되면 리소스의 낭비가 생길겁니다. useCallback을 이용해서 함수를 재선언하지않고 재사용 하도록 하였습니다.
App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import Input from "./Input"; | |
const App = () => { | |
return ( | |
<Input/> | |
) | |
} | |
export default App; |
실행화면

전체 소스코드는 Github에서 확인 가능합니다
https://github.com/hanhyung6376/learn-react/tree/master/use-callback
'웹 프로그래밍 > React' 카테고리의 다른 글
[React] useRef (0) | 2021.10.16 |
---|---|
[React] useEffect (0) | 2021.10.15 |
[React] useState (0) | 2021.10.12 |
[React] 외부 라이브러리 없이 캘린더 구현 (0) | 2021.10.11 |
[React] withRouter를 이용한 링크 이동시 메뉴변경 (0) | 2021.09.27 |