I know that react component will render everytime state changes and useCallBack memorize function depending on the dependency array provided.
But If I have this:
<input type="text" name="name" value={values.name} onChange={handleChange} />
<input type="text" name="phone" value={values.phone} onChange={handleChange} />
Whats the difference between these two handleChange implementation?
const handleChange = e => {
setValues(values => ({ ...values, [e.target.name]: e.target.value }))
}
and
const handleChange = useCallback(e => {
setValues(values => ({ ...values, [e.target.name]: e.target.value }))
}), [])
Code snippet needed in comment
const Child = () => {
console.log("Child rerendered");
return <div>Hello World </div>;
};
export default function App() {
const [count, setCount] = useState(0);
console.log("Parent rerendered");
return (
<div className="App">
<Child />
<button
onClick={() => {
setCount((x) => x + 1);
}}
>
{count}
</button>
</div>
);
}
The difference is that with the second one using useCallback, you'll keep using the first handleChange function you create; with the first one where you don't use useCallback, you're creating a new handler function each time. (Technically, you create a new one every time in both cases, but useCallback will only return the first one that gets created, because you've provided an empty dependency array.) More in the documentation.
It doesn't matter much when giving the handler function to input or other native HTML elements, or even simple components. If you were providing this handler function to a complex component, it might be better to use useCallback if that complex component optimizes re-rendering (for instance, with React.memo, PureComponent, or shouldComponentUpdate).