React Hook "useEffect" is called conditionally

react hooks example
react hooks vs redux
react hooks tutorial
react-hooks/exhaustive-deps
react hooks props
react hooks useeffect
react hooks uselayouteffect
react hooks componentdidmount

React is complaining about code below, saying it useEffect is being called conditionally:

import React, { useEffect, useState } from 'react'
import VerifiedUserOutlined from '@material-ui/icons/VerifiedUserOutlined'
import withStyles from '@material-ui/core/styles/withStyles'
import firebase from '../firebase'
import { withRouter } from 'react-router-dom'

function Dashboard(props) {
  const { classes } = props
  
  const [quote, setQuote] = useState('')

	if(!firebase.getCurrentUsername()) {
		// not logged in
		alert('Please login first')
		props.history.replace('/login')
		return null
	}

	useEffect(() => {
		firebase.getCurrentUserQuote().then(setQuote)
	})

	return (
		<main>
			// some code here
		</main>
	)

	async function logout() {
		await firebase.logout()
		props.history.push('/')
	}
}

export default withRouter(withStyles(styles)(Dashboard))

Your code, after an if statement that contains return, is equivalent to:

if(!firebase.getCurrentUsername()) {
    ...
    return null
} else {
    useEffect(...)
    ...
}

Which means that it's executed conditionally (only when the return is NOT executed).

To fix:

useEffect(() => {
  if(firebase.getCurrentUsername()) {
    firebase.getCurrentUserQuote().then(setQuote)
  }
}, [firebase.getCurrentUsername(), firebase.getCurrentUserQuote()])

if(!firebase.getCurrentUsername()) {
  ...
  return null
}

Hooks at a Glance – React, But what is a Hook? Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes —� React Hook Form is a tiny library without any dependencies. Performance Minimizes the number of re-renders and faster mounting, striving to provide the best user experience.

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. You can follow the documentation here.

I couldn't find the use case in the above code. If you need the effect to run when the return value of firebase.getCurrentUsername() changes, you might want to use it outside the if condition like:

useEffect(() => {
    firebase.getCurrentUserQuote().then(setQuote)
}, [firebase.getCurrentUsername()]);

Hooks API Reference – React, They let you use state and other React features without writing a class. Building your own Hooks lets you extract component logic into reusable functions. When we� React Hooks Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components.

The issue here is that when we are returning null from the if block, the useEffect hook code will be unreachable, since we returned before it, and hence the error that it is being called conditionally.

You might want to define all the hooks first and then start writing the logic for rendering, be it null or empty string, or a valid JSX.

Building Your Own Hooks – React, The introduction page used this example to get familiar with Hooks: import React, { useState } from 'react'; function Example() { // Declare a new state variable,� React hooks allows us to take a Reactjs functional component and add state and lifecycle methods to it. In simple words, React hooks are special functions to extend the capabilities of functional components and give them the possibility to have lifecycle events and manage state.

Using the State Hook – React, Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure� Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Building your own Hooks lets you extract component logic into reusable functions.

Rules of Hooks – React, Do Hooks replace render props and higher-order components? What do Hooks mean for popular APIs like Redux connect() and React Router? Do Hooks work� High-Quality & Affordable Courses - 30-Day Money Back Guarantee! Start Your Course Today. Join Over 90 Million People Learning Online at Udemy!

Hooks FAQ – React, Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. The Effect Hook lets you perform side effects in� Huge Selection and Amazing Prices. Free Shipping on Qualified Orders.

Comments
  • return null? from if condition? A component can only return valid JSX
  • @NatGeo null is a valid JSX expression stackoverflow.com/q/42083181/1176601 ... but the code after return is only executed when the if statement is false, similar to else { ... } - a.k.a. "conditionally" which is forbidden by rules-of-hooks
  • while true, this does not address the question.
  • Well.. I think this answer well addresses the question.