SukkaW / foxact

React Hooks/Utils done right. For Browser, SSR, and React Server Components.
https://foxact.skk.moe
MIT License
316 stars 12 forks source link

feat!: add force set value #6

Closed AprilNEA closed 1 year ago

AprilNEA commented 1 year ago

This will work well at certain times, such as a search box(swr) with debounced input is submitted by the user.

const Page = () => {
  const [debouncedKeyword, setDebouncedKeyword, forceSetValue] =
    useDebouncedState<string>("", 3000);

  const { data } = useSWR(
    debouncedKeyword ? ["/search", debouncedKeyword] : null,
    ([url, keyword]) =>
      fetch(url, {
        method: "POST",
        body: JSON.stringify({ keyword }),
      }).then((res) => res.json()),
  );

  return (
    ...
    <input onSumbit={(e)=> forceSetValue(e.target.value)} />
  )
}

I'm not sure this is correct or a best practice.

AprilNEA commented 1 year ago

Is the computational overhead here worth using useMemo like this?

  const clear = useCallback(() => {
    clearTimeout(timerIdRef.current);
    timerIdRef.current = undefined;
  }, []);

  const retimerWithClear = useMemo(() => {
    const retimerFn = retimer as RetimerType;
    retimerFn.clear = clear;
    return retimerFn;
  }, [retimer, clear]);

  return retimerWithClear
AprilNEA commented 1 year ago

Well, finally found what the problem is. 😭