简体   繁体   中英

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?

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)
  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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM