jollyjerr / react-autosave

Component or hook to auto save controlled form values as they are updated
https://www.npmjs.com/package/react-autosave
MIT License
65 stars 2 forks source link

OnSave gets called immediately after mounting #33

Open simon-lammes opened 3 months ago

simon-lammes commented 3 months ago

Summary

OnSave called is called twice immediately even though the value did not have time to change yet.

Reproduction

Within this project's example project put a console.log like this:

const unoptimizedSaveFunction = (data: string) => {
  console.log('saving: ', data);
  setValue(data);
};

When opening the example app in the browser, you will immediately see the following (without typing anything into the form):

saving:  hello world
saving:  hello world

Possible Causes

I could imagine that this is caused by Strict Mode re-running effects in development in development. There is an effect that is responsible for skipping the first render and saving on every subsequent render. If being called multiple times due to strict mode, it could cause the described behavior above. The effect looks like this:

useEffect(() => {
  if (initialRender.current) {
    initialRender.current = false;
  } else {
    handleSave.current(debouncedValueToSave);
  }
}, [debouncedValueToSave]);