When using class components it was always recommended to never do inline anonymous functions as its bad for performance i.e.
<input value{this.state.title}
onChange={(event) => this.setState({title: event.target.value})} />
You generally had to create a function outside of the render method called handleChange. This means that each render would NOT create a new inline anonymous function.
This brings me to functional components and useState etc..
The functional component is the render, so if I did this
[title, setTitle] = useState()
<input value{this.title}
onChange={(event) => this.setTitle({title: event.target.value})} />
It would be the same as creating a function because the function would be created each time anyway - inside a functional component
I know its possible to use the useCallback hooks to cache the function but its also recommended to not over use them as react is fast and using useCallback can actually be bad for simple cases.
So, this returns me to my original question.
Inside functional components should we be using inline anonymous functions ? Considering that creating a function inside a functional component would be created each time anyway.
I presume both are garbage collected anyway
Anybody know the recommended way ?
Thanks in advance
Inline functions are a good candidate for use in render prop and won't cause any performance concern.
Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.
Whereas, function components render the interface whenever the props are changed. Although we should prefer using function components most times as React also allows using state with function components in React version 16.8 and later by using the useState hook, which is also recommended by Meta (Facebook App) itself.
Inline function is a request to the compiler and an optimization technique used by the compiler. So, the answer is right, Inline functions are invoked at Compile time. Inline function is a combination of macro and function. Inline functions are like macros in c language.
Using inline arrow functions is the recommended way in React Docs - Hooks API Reference. (see below)
I think useCallback
would cause more of a performance impact then creating a new function each time.
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With