Home > Software design >  useEffect doesn't update the ui after running - typescript
useEffect doesn't update the ui after running - typescript

Time:04-13

I am having problems with useEffect and conditional rendering.

Basically I have code that uses useState hook named loggedIn, and it is false by default. And I have template like this:

<>
  {!loggedIn && (
    <div className="buttons d-flex justify-content-between">
        <Link to="/login" className="btn btn-warning rounded-0">Login</Link>
        <Link to="/register" className="btn btn-primary rounded-0">Register</Link>
    </div>
   )}
</>

and useEffect looks like this:

const [loggedIn, setLoggedIn] = useState(false)
useEffect(()=>{
    if(condition) {
        setLoggedIn = true
    } else {
        setLoggedIn = false
    }
}, [])

It doesn't hide after updating the value of loggedIn

CodePudding user response:

That is not how you use setState. Please follow the documentation of setState for more info. https://reactjs.org/docs/react-component.html#setstate

What you want to do is setLoggedIn(true) or setLoggedIn(false) based on your condition.

CodePudding user response:

You probably have to pass in the loggedIn, in the dependency array, this tracks state changes.

Try this:

const [loggedIn, setLoggedIn] = useState(false)
useEffect(()=>{
    if(condition) {
        setLoggedIn(true)
    } else {
        setLoggedIn(false)
    }
}, [condition])
  • Related