Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly implement a props callback function in the useEffect hook

I want to use useEffect() to detect changes to a state value and pass that value to a parent component using a callback function received as a prop. I can't figure out a way to do this without disabling the eslint missing dependency warning. I have this problem on both the child component and that child's child.

Here is the parent implementation:

const updateValues = (newValues) => {
  setValues({ ...values, ...newValues });
};

<GeneralUpdates onUpdate={updateValues} />

Here is the first child (GeneralUpdates):

const [values, setValues] = useState({
    name: '',
    description: '',
  });

// This handles form input changes
const handleChange = (prop) => (event) => {
  setValues({ ...values, [prop]: event.target.value });
};

useEffect(() => {
  onUpdate(values);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [values]);

<FilesUpload handleChange={onUpdate}/>

And this is the child's child (FilesUpload):

const [featuredPhotos, setFeaturedPhotos] = useState([]);

useEffect(() => {
  handleChange({ featuredPhotos });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [featuredPhotos]);

Adding handleChange as a dependency results in an infinite re-rendering loop. I've tried every solution I can find but must be missing something here.

like image 434
bshook Avatar asked Jun 21 '26 19:06

bshook


1 Answers

A colleague helped me find a solution to this—passing a named function to useEffect rather than the anonymous one:

const updateCallback = () => {
    onUpdate(values);
  };

useEffect(updateCallback, [values]);
like image 156
bshook Avatar answered Jun 23 '26 15:06

bshook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!