Question
Is the normal and expected behavior of a react reducer to ignore state updates in a some kind of "debounced" way?
I have implemented a snack where you can see that with 2 instant state updates via reducer, the screen is only rendered one time.
https://snack.expo.dev/oXd96Nbq8
Check the console logs. Why is this happening?
This is really annoying, since I can't run side-effects since the first state update is not detected? Any ideas?
Code
import React, { useReducer } from 'react';
import Constants from 'expo-constants';
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'toggle':
const newState = { count: state.count === 1 ? 0 : 1 };
console.log("Expected state", newState);
return newState;
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, initialState);
console.log("Rendered state", state);
const handleOnPress = () => {
dispatch({type: 'toggle'}); // 1 expected to be rendered... but not rendered because of the rollback?
try {
throw new Error("Forced error...");
} catch(err) {
console.log(err);
// Rollback
dispatch({type: 'toggle'}); // 0 expected to be rendered...
}
}
return (
<>
Count: {state.count}
<button onClick={handleOnPress}>toggle</button>
</>
);
}