Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation note that useEffect comparison is shallow #27

Closed
kevindice opened this issue May 29, 2019 · 2 comments
Closed

Add documentation note that useEffect comparison is shallow #27

kevindice opened this issue May 29, 2019 · 2 comments

Comments

@kevindice
Copy link

A use-case one might attempt is:

const [debouncedAddress] = useDebounce({
    address1,
    address2,
    country,
    city,
    state,
    zip,
}, 1500)

useEffect(() => {
    // do API call to update address on server
}, [
    debouncedAddress.address1
    debouncedAddress.address2
    debouncedAddress.country,
    debouncedAddress.city,
    debouncedAddress.state,
    debouncedAddress.zip,
])

...such that the form is auto-saved if the user has not typed in the last 1.5 seconds.

But in JS {} !== {} is true.

Suggesting the user use a hash function would be best. Otherwise, the above code example will trigger a re-render every 1500 ms. This should be accompanied w/ a note about the exhaustive-deps eslint rule.

@xnimorz
Copy link
Owner

xnimorz commented May 29, 2019

Thank you, @kevindice for your suggestion!

I'll add such note to the docs.

For your case, you can use useDebounceCallback, which is more configurable:

const [ debouncedAddress, setDeboucedAddress ] = useState({
    address1,
    address2,
    country,
    city,
    state,
    zip,
});

const [ callback ] = useDebounceCallback((newAddress) => {
  if (!deepEqual(newAddress, debouncedAddress)) {
    setDeboucedAddress(newAddress);
  }
}, 1500);

useEffect(() => {
    // do API call to update address on server
}, [
    debouncedAddress.address1
    debouncedAddress.address2
    debouncedAddress.country,
    debouncedAddress.city,
    debouncedAddress.state,
    debouncedAddress.zip,
])

@xnimorz
Copy link
Owner

xnimorz commented Jun 2, 2019

Added info in https://github.com/xnimorz/use-debounce#simple-values-debouncing section. Thank you again for the issue!

@xnimorz xnimorz closed this as completed Jun 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants