DEV Community

Discussion on: Post an Elegant Code Snippet You Love.

Collapse
 
thesmarthyena profile image
Philippe Skopal

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Without this pattern, the context value never changes.