user13618351
user13618351

Reputation:

Why the initial loading state is set to true while using useState?

I'm confused why the isLoading flag is set to true in the initial state. Isn't it supposed to be false initially? Consider this simple example:

const SearchCharity = () => {
  const [isLoading, setIsLoading] = useState(true)
  const [themes, setThemes] = useState([])

  useEffect(() => {
    const fetchThemes = async () => {
      try {
        setIsLoading(true)

        const result = await axios.get(url)
        setThemes(result.data.themes.theme)

        setIsLoading(false)
      } catch (err) {
        console.log(err)
      }
    }
    fetchThemes()
  }, [])

  return (
      {
        isLoading ? <h1>Loading......</h1> : <h1>Display Content</h1>
      }
    )

export default SearchCharity

Another thing it, if we set it to true or false initially in the above code, the useEffect still runs the same and the result on the screen will also be the same. So, why true? Is this some sort of standard?

Upvotes: 2

Views: 3823

Answers (3)

k-wasilewski
k-wasilewski

Reputation: 4643

You are asking about the reason that you did set this initial value yourself :)

Most certainly you copied that code from somewhere and the reason the isLoading's initial state is set to true is that your whole component actually is in such state initially and then you set it to false after fetched data is ready.

Upvotes: 1

Stanley Pierre Louis
Stanley Pierre Louis

Reputation: 41

  const [isLoading, setIsLoading] = useState(true)
  const [themes, setThemes] = useState([])

  useEffect(() => {
    const fetchThemes = async () => {
      try {
        const result = await axios.get(url)
        setThemes(result.data.themes.theme)

        setIsLoading(false)
      } catch (err) {
        console.log(err)
      }
    }
    fetchThemes()
  }, [])

  return (
      {
        isLoading ? <h1>Loading......</h1> : <h1>Display Content</h1>
      }
    )

export default SearchCharity

More info: https://reactjs.org/docs/handling-events.html

Upvotes: 1

Shmili Breuer
Shmili Breuer

Reputation: 4147

The value you pass when initializing state is up to you.

If you want it to be initialized as true you pass true like this.

const [isLoading, setIsLoading] = useState(true)

If you want you can also pass false and it will be initialized as false

const [isLoading, setIsLoading] = useState(false)

Upvotes: 5

Related Questions