React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

Viewed 11961

What i'm doing is creating an authentication system with react hooks. However, when I declare and call a constant using a react component it returns the error below. What is the right place to declare a constant and / or a function?

Error: React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

function handleSubmit({email, password}) {
  dispatch(signInRequest(email, password));
}

const dispatch = useDispatch();



class Login extends React.Component {
  render() {
    return (
      <>
        //Other code here
      </>
    );
  }
}

export default Login;
2 Answers

You can't call react hooks outside functional component or in class component. https://reactjs.org/docs/hooks-rules.html


const Login = () => {
  const dispatch = useDispatch();
  function handleSubmit({email, password}) {
      dispatch(signInRequest(email, password));
  }
  render() {
    return (
      <>
        //Other code here
      </>
    );
  }
}

export default Login;

You are using a class component and you are trying to use hook which will never wrong. Hooks should be called inside the functional component like:

const Login = () => {
 const dispatch = useDispatch();

function handleSubmit({email, password}) {
  dispatch(signInRequest(email, password));
}

    return (
      <>
        //Other code here
      </>
    );
  
}

export default Login;
Related