<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
function ComponentWithInlineFunction() {
const clickMe = evt => evt.preventDefault();
return React.createElement('button', {onClick: clickMe}, 'Click me!');
}
function ComponentWithUseCallback() {
const clickMe = React.useCallback(evt => evt.preventDefault(), []);
return React.createElement('button', {onClick: clickMe}, 'Click me!');
}
ReactDOM.render(React.createElement(ComponentWithInlineFunction), document.getElementById('root'))
ReactDOM.render(React.createElement(ComponentWithUseCallback), document.getElementById('root'))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Inline | |
Hooks |
Test name | Executions per second |
---|---|
Inline | 285082.2 Ops/sec |
Hooks | 429352.5 Ops/sec |
Let's break down the benchmark and its results.
What is being tested?
The benchmark tests two approaches to handling event handling in React applications:
onClick
handler is defined inline within the component's render method. This means that every time the component is re-rendered, a new function object is created and assigned to the onClick
property of the button element.onClick
handler is defined using the useCallback
hook from React. The useCallback
hook memoizes the function so that it's not recreated on every render.Comparison of options
The two approaches have different performance characteristics:
useCallback
, React ensures that the function is only recreated when its dependencies change. This can provide better performance, especially in applications with a large number of event handlers.Pros and cons
useCallback
hook from React.Library and its purpose
In this benchmark, React is used as a library for building the components. The ReactDOM.render()
method is used to render the React component tree into the DOM.
Special JS feature or syntax
The useCallback
hook is a special JavaScript feature introduced in React 16.8. It allows you to memoize functions so that they're not recreated on every render.
Other alternatives
If you prefer not to use the useCallback
hook, you can create your own solution using other techniques, such as:
memoize
function for memoizing functions.However, these alternatives may require more boilerplate code and may not provide the same level of performance benefits as using the useCallback
hook.