React: Using reducer/state inside useEffect()

Created on 2 Dec 2018  路  3Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
This may be a bug or the way useEffect() works.

What is the current behavior?
State values are not updated when used inside an effect (the effect is intended to be executed only once)

import React, {useEffect, useState} from 'react'

const App = (props) => {
  const [count, setCount] = useState(0)

  useEffect( () => {
    const interval1 = setInterval(() => {
      console.log('interval 1:', count) //output 'interval 1: 0'
    }, 4000)

    return () => {
      clearInterval(interval1)
    }
  }, [])

  return (
    <div className="App">
      {count}
      <button onClick={() => setCount(count+1)}>Count</button>
    </div>
  )
}

export default App;

The code would work as expected when useEffect( () => {...}) is used without watching for [], but then the interval would go thru new subscriptions cycles for every state change. Is this an expected behavior?

I am sort of experimenting to use rxjs to subscribe to certain events that looks at state/reducer values.

*Which versions of React, and which browser / OS are affected by this issue? *
"react": "^16.7.0-alpha.2"

Most helpful comment

@babloo80 : the behavior is expected based on the way you've written that. The dependencies array argument to useEffect is empty, therefore only the function and closure defined in the initial call are going to be used.

Dan discussed the difficulties using intervals with useEffect in this Reddit thread:

https://www.reddit.com/r/reactjs/comments/a1u8do/confused_about_the_useeffect_hook/

All 3 comments

@babloo80 : the behavior is expected based on the way you've written that. The dependencies array argument to useEffect is empty, therefore only the function and closure defined in the initial call are going to be used.

Dan discussed the difficulties using intervals with useEffect in this Reddit thread:

https://www.reddit.com/r/reactjs/comments/a1u8do/confused_about_the_useeffect_hook/

@markerikson, would you like me to close this issue? My current workaround is to get the latest value of the state / reducer from another effect and ship it thru the streams (with some sort of control stream to send state values).

But a general question is, how to perform a force refresh like operation on state / reducer hook to get the latest value (inside a method or on an useEffect above?

I wrote a bit about this here. There are also other more recent discussions.

https://overreacted.io/making-setinterval-declarative-with-react-hooks/

I don't think there's anything directly actionable so I'll close.

Was this page helpful?
0 / 5 - 0 ratings