Home > Software engineering >  Custom hook with react - dont know whats wrong with this one?
Custom hook with react - dont know whats wrong with this one?

Time:11-27

I'm trying been more simlicity but i still learn the power of custom hook. i'm trully not understand whats wrong with my hook.

const UseMessage = (msg: string, delay: number, cb?: () => void): [setCB: () => void] => {
  const [message, setMessage] = useState("");

  const setCB = () => {
    setMessage(() => msg);
    setTimeout(() => {
      setMessage(() => msg);
      if (typeof cb === "function") {
        cb();
      }
    }, delay);
  };

  return [setCB];
};

export default UseMessage;

i'm getting error :Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

CodePudding user response:

Custom hook names should always start with lower case use (see beta docs), so change to useMessage.

CodePudding user response:

There are two things which can resolve your problem, here:

  1. First, name your hook with lowercase use and not uppercase. The reason for that is it is wrong according to the React docs.
  2. Here, your UseMessage is not a custom hook for React, just a javascript function. Inside it, you are using useState which is a hook and React won't allow that. The reason is the next point.
  3. Second, according to the rules of React you can utilise any hook only inside the body of a function component or inside the body of another hook function.
  • Related