first-time poster here. I'm pretty new to React & JS in general, and I've been working in NextJS. Interestingly, my project runs just fine when I run next dev
, but fails when I use next build
.
I get the following error:
Error: React Hook "useFunction" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. react-hooks/rules-of-hooks
What's interesting about useFunction
is that it is not a Hook - I define it as a function in the same file as a component FunctionButton
like so and use it as part of the onClick
event handler
const useFunction = async () => {
const result = await someStuff();
return result
}
const FunctionButton = () => {
return <Button onClick={() => useFunction()}>Click Me</Button>;
};
export default FunctionButton;
Any idea why this isn't building successfully? Thanks in advance!
CodePudding user response:
The reason that it thinks useFunction
is a hook is because that's how React's linting checks work. They rely on the use prefix to determine that it's a hook:
We provide an ESLint plugin that enforces rules of Hooks to avoid bugs. It assumes that any function starting with ”use” and a capital letter right after it is a Hook.
So, merely because your function starts with use
, React takes it to be a hook. A solution would be to rename your function or add an eslint-ignore
comment.
CodePudding user response:
React considers the files whose name starts with the word use
as hooks even though they aren't.
There are to ways to solve the issue:
- simply rename your file. (does not start with
use
) - add
/* eslint-disable */
block comment at the top of the file.