0
    import React, { useState } from "react";
    import { Redirect } from "react-router-dom";
    
    function Update(data) {
       if(!data.location.state) return <Redirect to="/"/>
       const [name, setName] = useState(data.location.state.name);
       return (<>Hello World</>)
}

Error : React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks

  • Does this answer your question? [React Hook "useEffect" is called conditionally](https://stackoverflow.com/questions/57620799/react-hook-useeffect-is-called-conditionally) – Aniket Kolekar Jun 12 '21 at 19:27

2 Answers2

1

Move the useState to the top of the function (above the if condition) or move the if condition inside useEffect and redirect from there.

function Update(data) {
 const [name, setName] = useState(data.location.state.name);
     
 if(!data.location.state) {
      return <Redirect to="/"/>
 }

  return (<>Hello World</>)
}
Aniket Kolekar
  • 829
  • 5
  • 18
1

(Similar Stack Overflow question that might include helpful answers.)

From the docs:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

So the useState hook call should be moved to the top of the component.

You could do:

import React, { useState } from "react";
import { Redirect } from "react-router-dom";
    
function Update(data) { 
  const [name, setName] = useState(
    data.location.state ? data.location.state.name : ''
  );

  if(!data.location.state) return <Redirect to="/"/>

  return (
    <>Hello World</>
  );
}
H. Almidan
  • 361
  • 3
  • 9