<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
function ComponentWithInlineFunction() {
const [state, setState] = React.useState('test');
const clickMe = evt => {
evt.preventDefault();
console.log(state);
}
return React.createElement('button', {
onClick: clickMe
}, 'Click me!');
}
function ComponentWithUseCallback() {
const [state, setState] = React.useState('test');
const clickMe = React.useCallback(evt => {
evt.preventDefault();
console.log(state);
}, [state]);
return React.createElement('button', {
onClick: clickMe
}, 'Click me!');
}
function ComponentWithInlineClick() {
const [state, setState] = React.useState('test');
return React.createElement('button', {
onClick: (e) => {
evt.preventDefault();
console.log(state);
},
}, 'Click me!');
}
ReactDOM.render(React.createElement(ComponentWithInlineFunction), document.getElementById('root'))
ReactDOM.render(React.createElement(ComponentWithUseCallback), document.getElementById('root'))
ReactDOM.render(React.createElement(ComponentWithInlineClick), document.getElementById('root'))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Inline function | |
Hooks | |
Inline code |
Test name | Executions per second |
---|---|
Inline function | 1049318.5 Ops/sec |
Hooks | 1272050.6 Ops/sec |
Inline code | 1012741.5 Ops/sec |
Let's break down what's being tested in the provided JSON.
The benchmark is comparing three different approaches to handle events in React applications:
React useCallback
: This hook allows you to memoize a function so that it's not recreated every time the component re-renders. In this case, clickMe
is a function that prevents default behavior and logs the state.clickMe
function is defined directly in the JSX.(e) => { ... }
) instead of the traditional function syntax.Here are some pros and cons of each approach:
React useCallback
:Now, let's talk about some other considerations:
clickMe
, so this shouldn't be a significant factor.Finally, let's talk about some other alternatives:
React useCallback
or inline functions, you could use a HOC to wrap your component and provide the clickMe
function. This can be a useful technique for handling events in React.In summary, the benchmark is comparing three different approaches to handle events in React applications: React useCallback
, inline functions, and inline code with ES6 syntax. Each approach has its pros and cons, and understanding these differences can help you choose the best approach for your use case.