rrousselGit / flutter_hooks

React hooks for Flutter. Hooks are a new kind of object that manages a Widget life-cycles. They are used to increase code sharing between widgets and as a complete replacement for StatefulWidget.
MIT License
3.13k stars 179 forks source link

Add hook useDeferredValue #394

Closed itisnajim closed 10 months ago

itisnajim commented 10 months ago

trying to write an equivalent for react useDeferredValue hook.

rrousselGit commented 10 months ago

Hello!

I'm not sure if that's really an equivalent to the React one. I've never used it, but reading the docs, it seems like this deprioritise the subsequent render, such that it doesn't block the UI thread. A simple setState after a timeout wouldn't do that.

itisnajim commented 10 months ago

Hello!

I'm not sure if that's really an equivalent to the React one. I've never used it, but reading the docs, it seems like this deprioritise the subsequent render, such that it doesn't block the UI thread. A simple setState after a timeout wouldn't do that.

yes it's not really equivalent to the react one, The background re-rendering process triggered by useDeferredValue happens as soon as React finishes the initial render, and the timeout can be set also, in react e.g:

const deferredCount = useDeferredValue(count, {
    timeoutMs: 1000,
  });

in the code i've pushed it resembles more of a debounce mechanism, Maybe by incorporating WidgetsBinding.instance.addPostFrameCallback we can ensure that the layout is completed.. still, I'm unsure about how to automatically manage and emit the timeout property in this context.

rrousselGit commented 10 months ago

As it is, wouldn't usePrevious be a good-enough replacement?

itisnajim commented 10 months ago

usePrevious can't control the timeout meaning it doesn't wait for a specific duration. defer the update of a value for a specified timeout this can be beneficial for optimizing the rendering performance by delaying non-critical updates. e.g: scenario where you have a search input component that triggers an API call for search suggestions. U can use useEffect with deferred.value as a dependency

useEffect(() {
  // Use deferredQuery for your API call
  fetchSuggestions(deferredQuery);

  // Cleanup function
  return () {};
}, [deferredQuery]);
rrousselGit commented 10 months ago

I'm still skeptical whether that's really equivalent.

At the moment, the current implementation is only equivalent to a debounce/throttle. Yet the documentation of useDeferredValue is pretty clear in that it's different from a simple debounce/throttle

rrousselGit commented 10 months ago

I would be more willing to add a simple "useDebounced" hook with an implementation similar to the current one.

This would avoid possible confusions in case someone familiar with the useDeferredValue hook tries to use flutter_hooks'