React Hook “useEffect” is called conditionally – Code Example

Total
0
Shares

React hooks are needed to be executed in the same order as they are defined. This should happen at each render of the component. But if you use hooks like useEffect() inside conditions, loops, nested functions then their execution will depend on the execution of those conditions or loops. This will throw an error – React Hook “useEffect” is called conditionally.

The same error might occur when the function terminates before executing the hooks. For example, you used an if condition before useEffect() and returning from that condition. Now if the condition is true then component will return and useEffect() will never run. This is error. Check this code –

function checkLogIn(props) {
    const [logIn, setLogIn] = useState(props.isLoggedIn)

    if(props.isLoggedIn) {
        return <p>Already Logged In</p>
    }

    useEffect(() => {
        setLogIn(true)
    })

    return(<p>Logged In</p>)
}

In this code if the value of props.isLoggedIn is true, then useEffect() will not run and checkLogIn() function will terminate. This is not acceptable.

Solution with Code Example

Always declare all the hooks at the top and then your rest of the code. In the above code, we were getting the error. But we can modify it to satisfy hooks requirements as well as our own logic –

function checkLogIn(props) {
    const [logIn, setLogIn] = useState(props.isLoggedIn)

    useEffect(() => {
        if(!props.isLoggedIn) {
            setLogIn(true)
        }
    })

    if(props.isLoggedIn) {
        return <p>Already Logged In</p>
    }

    return(<p>Logged In</p>)
}