I am very new to React and I am trying to create a hook and call it from the onSubmit event but it gives me an error.
My code for the onSubmit function is the following:
const onSubmit = ( event ) => {
event.preventDefault();
setFormSubmited( true );
if( !isFormValid ) return;
const { send, setMessageuseMail } = useMail();
}
The hook I created is called useMail and it is this
import { useState } from "react"
export const useMail = () => {
const [send, setSend] = useState(false);
const [messageMail, setMessageMail] = useState();
setSend( true );
setMessageMail(' Pruebas ');
return {
send,
messageMail
}
}
and the error it gives me is this:
ERROR
[eslint] srccomponentsContactUs.jsx
Line 43:45: React Hook "useMail" is called in function "onSubmit" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
I already tried to remove the word "use" from the file and I couldn’t make it work, could you please help me?
3
Answers
Change your component name to
UseMail
.React components must start with uppercase letter as error clearly shows.
You need to move the call to
useMail
outside of theonSubmit
function.React hooks need to be called at the top-level so they are called each time the component renders and in the same order.
Check out the documentation for the rules for hooks: https://legacy.reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
The error message is saying React hooks must be called from either a component or another hook. If
onSubmit
is one of these, it needs to be updated to comply with the naming convention (capital for component,use
for hooks). But in this caseonSubmit
isn’t so we need to move where we’re calling the hook.The error you’re encountering is due to the fact that React hooks, including custom ones like
useMail
, should only be called at the top level of a React function component or another custom hook. You are calling theuseMail
hook inside theonSubmit
function, which violates the rules of hooks.Here’s how you can refactor your code to address this issue:
By moving the
useMail
hook call outside of theonSubmit
function and calling it at the top level of the component, you should no longer encounter the "React Hook" error.