1) why does it render components quicker?
- the performance gain of second code is not come from functional
setState()
- you use
useCallback()
to memorize the function onRemove()
, so it won't be created every time the component re-render
.
- you pass no dependencies, so the function
onRemove()
will be created only once - when the component mounts
2) What are the other advantages of using functional setState()?
functional setState()
is used to escape closure
import React, { useState, useEffect } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
console.log('render');
useEffect(() => {
console.log('componentDidUpdate')
const id = setInterval(() => {
setCount(count) // count is always 0 because the variable count is closured
}, 1000);
return () => {
clearInterval(id);
console.log('clean');
}
}, []); // run only once when the component mounts
return (
<h1>
{count}
</h1>
)
}
export default Counter;
- use functional
setState()
to read fresh state
import React, { useState, useEffect } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
console.log('render');
useEffect(() => {
console.log('componentDidUpdate')
const id = setInterval(() => {
setCount(count => count + 1); // read fresh value of count
}, 1000);
return () => {
clearInterval(id);
console.log('clean');
}
}, []); // run only once when the component mounts
return (
<h1>
{count}
</h1>
)
}
export default Counter;
Reference