0

Hello :)) I not familliar with custom hook in React. I have tried simple ones, but example below I don't know how to resole

I want write a hook that will work similarly to useState, except that it should update the state only when the new value is different from the previous one.

The first hook parameter should be the default state value.

The second optional hook parameter should be a function that compares these values. If both values are equal, this function should return true. If the function is not passed, then the comparison of the values will take place using a simple comparison.

Thanks for your help :)

skyboyer
  • 22,209
  • 7
  • 57
  • 64
McKrus
  • 37
  • 2
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO and elsewhere, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mre] showing your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Nov 14 '22 at 08:22
  • *"...except that it should update the state only when the new value is different from the previous one...."* That's what `useState` does, using an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. – T.J. Crowder Nov 14 '22 at 08:22
  • How about going through tutorials? – Harun Yilmaz Nov 14 '22 at 08:24

1 Answers1

0

If you want this?
You can easy to paste this code.
https://bokboot.net/read?id=51&key=4b9b39e1-9389-495d-a5e2-673c818b6514

import { useCallback, useState } from "react";

const useCompare = (defaultValue: string) => {
  const [content, setContent] = useState(defaultValue);
  const [isSame, setIsSame] = useState(false);

  const onChange = useCallback((value: string) => {
    if (content == value) return setIsSame(true);
    setIsSame(false);
    setContent(value);
  }, []);

  const onReset = useCallback(() => {
    setIsSame(false);
    setContent("");
  }, []);

  return [content, isSame, onChange, onReset] as [
    string,
    boolean,
    typeof onChange,
    typeof onReset
  ];
};
export default useCompare;
ryuhojin
  • 66
  • 4