0

Given the input

<input
    ref={inputRef}
    className={styles.input}
    onBlur={handleDoneChange}
    type='text'
    value={newValue}
    onChange={handleChange}
    onKeyDown={handleKeyDown}
/>

I saw a piece of code that put some handler (handleChange, handleDoneChange) in useCallback, some not (handleKeyDown), as in the following:

const handleChange = useCallback((e) => {
    setNewValue(e.target.value);
}, []);

const handleDoneChange = useCallback(() => {
    changeName();
}, [newValue, router.query.id]);

const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
        changeName();

        e.target.blur();
    }

};

Should I put handleKeyDown in useCallback, if not, what are the possible reasons?

william007
  • 17,375
  • 25
  • 118
  • 194
  • If they're not being passed down to other components other than the ``, there isn't really any reason to - it won't cause excess rerenders and there's no performance issue – CertainPerformance May 15 '22 at 00:11
  • Thank @CertainPerformance, what if this input field is inside another component? Will the rerendering of that component cause the recreation of function and make the onCallback necessary? – william007 May 15 '22 at 01:23
  • Even if it's in another component, it's quite unlikely to be an issue. You might eventually run into a situation where it's causing a problem but it's not worth worrying about until then – CertainPerformance May 15 '22 at 01:30
  • Thanks @CertainPerformance, if I wrap all handleKeyDown etc. in useCallback, would it be a bad practice? as it can have potential performance gain (without recreating the function), while there is no much issue as I can see. – william007 May 15 '22 at 01:36
  • I found a link here - https://kentcdodds.com/blog/usememo-and-usecall - I think it clears my doubt. In case in future anyone bump into this - and detailed enough to browse through the comments. – william007 May 15 '22 at 02:00

0 Answers0