React Hook delayed useEffect firing?

Robert Templeton picture Robert Templeton · Sep 4, 2019 · Viewed 7.5k times · Source

I am trying to use useEffect() in my react hook to update the state when my props change. but there is a delay and the useEffect is only firing after I click again on an element in my hook. Im fairly new to using hooks and any help would be appreciated. Thanks

function ImageOrderSelect (props) {
  const [clicked, setClicked] = useState(false)
  const [options, setOptions] = useState(props.options)
  const [current, setCurrent] = useState(props.current)

  useEffect(() => {
      setCurrent(props.current)
    }, [props.current])


  if(!clicked){
    return (
        <div className="image-order-select-icon" onClick={() => setClicked(!clicked)}>
            <FontAwesomeIcon size="lg" icon={faCircle} />
            <p>{current}</p>
        </div>
    )
  } else if(clicked){
      return (
          <div className="image-order-select">
              {optionsList}
          </div>
      )
  }


}

Answer

Abu Dujana Mahalail picture Abu Dujana Mahalail · Jan 7, 2020
    useEffect(() => {

      setTimeout(()=>{
       setCurrent(props.current)
      }, 1000)

    }, [props.current])

You just need to add timeout/delay before displaying the current...