ReactのRender Hooks Pattern
これを見て初めて知った。
https://engineering.linecorp.com/ja/blog/line-securities-frontend-3/
カウンターサンプルを作って違いを検証してみる。仕様としては
現在のカウントを表示
インクリメントするボタンあり
現在の値を外から参照したい
にする。
まず普通に実装する(俺はこれがスタンダードな方だと思っている)。
code:jsx
const Page = () => {
const count, setCount = useState(0);
return (
<>
<SimpleCounter onChange={setCount} />
現在の値は{count}
</>
);
};
const SimpleCounter = ({ onChange }: { onChange: (count: number) => void }) => {
const count, setCount = useState(0);
const onClick = useCallback(() => {
setCount((c) => c + 1);
}, []);
useEffect(() => {
onChange(count);
}, onChange, count);
return (
<h1>
SimpleCounter: {count} <button onClick={onClick}>+</button>
</h1>
);
};
次にRender Hooks Pattern
code:jsx
import React, { useCallback, useState } from "react";
const Page = () => {
const count, CounterA = useCounter();
return (
<>
<CounterA />
現在の値は{count}
</>
);
};
const useCounter = (): number, () => JSX.Element => {
const count, setCount = useState(0);
const Counter = () => {
const onClick = useCallback(() => {
setCount((c) => c + 1);
}, []);
return (
<h1>
useCounter: {count} <button onClick={onClick}>+</button>
</h1>
);
};
return count, Counter;
};
Render Hooks Patternでは