I found a simple way, to overcome the context limitation of a setInterval. Demo here: codesandbox.io/s/demosetintervalco...
import React, { useEffect, useState, useReducer } from "react"; import "./styles.css"; const initialState = { count: 0 }; // The reducer function function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; default: return { count: state.count }; } } export default function App() { const [count, setCount] = useState(0); const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { const interval = setInterval(() => { setCount(count + 1); dispatch({ type: "increment" }); console.log("Count no reducer:", count); console.log("Count with reducer: ", state.count); }, 1000); return () => clearInterval(interval); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <div className="App"> <h1>Count no reducer: {count}</h1> <h1>Count with reducer: {state.count}</h1> </div> ); }
Without this pattern, the context value never changes.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I found a simple way, to overcome the context limitation of a setInterval.
Demo here: codesandbox.io/s/demosetintervalco...
Without this pattern, the context value never changes.