const Counter = () => {
	const [count, setCount] = useState(0);
 
  const handleOnPress = () => setCount(count + 1)
 
  return (
  <>
    <span>{count}</span>
    <button onPress={handleOnPress} />
  </>
  )
}

まず最適化したいコンポーネントをuseMemoで囲う。

const Counter = () => {
	const [count, setCount] = useState(0);
 
  const handleOnPress = () => setCount(count + 1)
 
  return useMemo(() => (
  <>
    <span>{count}</span>
    <button onPress={handleOnPress>
  </>
  ), [])
}

すると依存引数を書く必要が出てくるので書く。

const Counter = () => {
	const [count, setCount] = useState(0);
 
  const handleOnPress = () => setCount(count + 1)
 
  return useMemo(() => (
  <>
    <span>{count}</span>
    <button onPress={handleOnPress>
  </>
  ), [count, handleOnPress])
}

依存引数に関数がある場合、コンポーネントの再renderで関数の参照が変わるのを防ぐため、useCallbackで依存関数ラップすることで不要なrenderを防ぐことができる。

const Counter = () => {
	const [count, setCount] = useState(0);
 
  const handleOnPress = useCallback(
		() => setCount(count + 1),
		[count, setCount]
)
 
  return useMemo(() => (
  <>
    <span>{count}</span>
    <button onPress={handleOnPress>
  </>
  ), [count, handleOnPress])
}