I'm currently very amazed about the use cases of the new react hooks API and what you can possibly do with it.
A question that came up while experimenting was how expensive it is to always create a new handler function just to throw it away when using useCallback
.
Considering this example:
const MyCounter = ({initial}) => {
const [count, setCount] = useState(initial);
const increase = useCallback(() => setCount(count => count + 1), [setCount]);
const decrease = useCallback(() => setCount(count => count > 0 ? count - 1 : 0), [setCount]);
return (
<div className="counter">
<p>The count is {count}.</p>
<button onClick={decrease} disabled={count === 0}> - </button>
<button onClick={increase}> + </button>
</div>
);
};
Although I'm wrapping the handler into a useCallback
to avoid passing down a new handler every time it renders the inline arrow function still has to be created only to be thrown away in the majority of times.
Probably not a big deal if I only render a few components. But how big is the impact on performance if I do that 1000s of times? Is there a noticeable performance penalty? And what would be a way to avoid it? Probably a static handler factory that only gets called when a new handler has to be created?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…