1

I am looking at an example in the documentation of fluentui:

...
export const TextFieldControlledExample: React.FunctionComponent = () => {
  const [firstTextFieldValue, setFirstTextFieldValue] = React.useState('');
  ...
  const onChangeFirstTextFieldValue = React.useCallback(
    (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => {
      setFirstTextFieldValue(newValue || '');
    },
    [],
  );
  ...
  return (
  ...
      <TextField
        label="Basic controlled TextField"
        value={firstTextFieldValue}
        onChange={onChangeFirstTextFieldValue}
        styles={textFieldStyles}
      />
  ...
  );
};

Why are they using React.useCallBack here instead of a normal function? E.g. what is there to memoize?

O. Altun
  • 685
  • 7
  • 20
  • This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders. One time someone said it was kind of a best practice using this hook, but i can't confirm that. – Andre Sampaio Mar 02 '21 at 12:50

1 Answers1

1

when you create a function at your component that function will be recreated at every rerender for that component.

When you apply useCallback you memoize that function, which avoids the function being recreated at every rerender. It will only create a new function if at your dependencies array any of that dependencies values change.

It's important to note, that if you reference some state at your memoized function you may face a stale state, leading to undesired behavior. In these cases using a setState with a callback function would avoid that issue.

buzatto
  • 9,704
  • 5
  • 24
  • 33