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

Syed Ashraf
  • 102
  • 1
  • 7
  • 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

3 Answers3

2

(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
  • 431
  • 4
  • 9
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
  • 383
  • 6
  • 19
0
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
    
function Update(data) { 
  const [name, setName] = useState(
    data.location.state ? data.location.state.name : ''
  );

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

  return (
    <>Hello World</>
  );
}
blockhead
  • 364
  • 3
  • 18