This is a question regarding a possible performance hit while using hooks.
Quoting useState example from react docs:
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>
</>
);
}
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
I have two queries regarding the usage of useState :
- What does
identity is stable and won’t change on re-rendersmean ? - I can see that for each button an
anonymousfunction is passed as event handler. Even ifsetState identity is stableas claimed by React is true, wouldn't the anonymous function be re-created at every re-render ?
Wouldn't it be more efficient if useCallback was used to define memoized functions and use them as event handlers ?