Reputation: 1046
Is there a way to initiate state to true, then change to false after x amount of time within useState
?
Currently looks like this:
const [scrollDown, setScrollDown] = useState(true)
setTimeout(() => {
setScrollDown(false)
}, 2000)
Looking to do something like this, but syntax doesn't appear to be correct:
const [scrollDown, setScrollDown] = useState(() => {
setScrollDown(true)
setTimeout(() => {
setScrollDown(false)
}, 2000)
})
Trying this as well:
const [scrollDown, setScrollDown] = useState(true, () => {
setTimeout(() => {
setScrollDown(false)
}, 1000)
})
Upvotes: 0
Views: 1835
Reputation: 1046
Like others have mentioned, using useEffect
works best so I went with this solution. My issue initially was passing that second empty array arg:
const [scrollDown, setScrollDown] = useState(true)
useEffect(() => {
setTimeout(() => {
setScrollDown(false)
}, 1000)
}, [])
Upvotes: 1
Reputation: 53
I'm afraid both of the code snippets you mentioned are not correct. useStates expects the value but we're returning nothing. Also, we can't pass second argument to useState. Your best bet would be to utilize useEffect that runs on first render only. There you can place your timeout.
Upvotes: 0