React useEffect and setInterval: Why console.log always prints 0

React useEffect and setInterval: Why does console.log always print 0? While working with React Hooks, a common point of confusion appears when using setInterval inside useEffect. Problem scenario: useEffect(() => { setInterval(() => { console.log(count) setCount(prev => prev + 1) }, 1000) }, []) Observed behavior: The UI updates correctly and count increments every second However, console.log(count) always prints 0 Root cause: This is not a React issue. It is a result of JavaScript closures combined with an empty dependency array. useEffect([]) runs only once, during the initial render At that time, count is 0 The function passed to setInterval captures (closes over) this initial value As a result, console.log(count) always references the stale state Why the state still updates: The state update uses the functional form: setCount(prev => prev + 1) React guarantees that prev always represents the latest state, which is why the UI continues to update correctly. Recommended approach: When working with intervals, timeouts, or subscriptions, always rely on functional updates or refs instead of directly accessing state variables. Key takeaway: Many React “bugs” are actually misunderstandings of JavaScript fundamentals such as closures and execution context. Understanding this distinction is essential for writing predictable and maintainable React code. #ReactJS #JavaScript #FrontendDevelopment #ReactHooks #useEffect #SoftwareEngineering #WebDevelopment

  • text

Nice breakdown 👌 In cases like this, do you prefer useRef or functional updates when the logic becomes more complex?

Add count in dependency array

See more comments

To view or add a comment, sign in

Explore content categories