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:
- First, name your hook with lowercase
use
and not uppercase. The reason for that is it is wrong according to the React docs. - Here, your
UseMessage
is not a custom hook for React, just a javascript function. Inside it, you are usinguseState
which is a hook and React won't allow that. The reason is the next point. - 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.