Search code examples
javascriptreactjstimeout

How to check state and execute function after some delay in React?


I am trying to execute a function if the state doesn't change which is updated due to database fetch. I mean:

const [value, setValue] = useState(false)
const func = () => {
  ...
}

setTimeout(()=>{
  if(!value) {
     func()
  } else {
    // Alert.alert("Nothing!")
     funcWithoutDbOperations() // which is desired
  }
},20000)

fetchData.then(()=>setValue(true))

But this timeout method takes the initial state of the const value, and executes due to its initial value, not depending its value after 20 seconds. Even if it updates to true.

How can I achieve this object?


Solution

  • You need to use Ref.

    const [value, setValue] = useState(false)
    const valueRef = useRef(value)
    valueRef.current = value;
    
    const func = () => {
      ...
    }
    
    setTimeout(()=>{
      if(!valueRef.current) {
         func()
      } else {
        // Alert.alert("Nothing!")
         funcWithoutDbOperations() // which is desired
      }
    },20000)
    
    fetchData.then(()=>setValue(true))