简体   繁体   中英

Implementing time delay using React Hooks

I would like to know how to implement time delay in React functional component. Pseudocode is given below

const staring_function = () => {
  return(
    //renders components
  )
}
const main_function = () => {
  return(
    //renders components
  )
}

I would like to run starting_function for 3 seconds to render some texts on the screen on loading after which the main_function run to replace the contents of the starting_function. for example the page displaying a text "LOADING... " for few seconds and then displaying the contents.

I have been working on this for some days yet still cant get around. I know it has something to do with useEffect hook. It would have been helpful if someone could help me out. Thank you

You don't need useEffect hook. Try following code:

const [ loading, setLoading ] = useState(true)

setTimeout(() => {
  console.log('now')
  setLoading(false)
}, 3000)

if (loading) {
  return (
    <div>LOADING...</div>
  )
}

return (
  <div>content</div>
)

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