This is very fundamental but need deep analysis, wic one is better approach.
In this code we are setting setState in onCheckChange, without useCallback.
const App = () => {
const [checked, setChecked] = useState(false)
// Without UseCallback
const onCheckChange = () => {
setChecked(!checked);
};
return (
<div className="App">
<input type="checkbox" onChange={onCheckChange} checked={checked} />
</div>
);
}
In this code state will be updated through useCallback to avoid re-creation of onCheckChange
const App = () => {
const [checked, setChecked] = useState(false)
// Callback to update Sate
const onCheckChange = useCallback(() => {
setChecked(checked => !checked);
}, [setChecked]);
return (
<div className="App">
<input type="checkbox" onChange={onCheckChange} checked={checked} />
</div>
);
}
Top comments (0)