My example works as follows:
I have a button that shows an image (via state change by dispatch from useReducer) for 400ms when clicked. After 400ms the image is hidden again and the button is visible. On the desktop browser this works quite well. But on mobile there are problems with the performance. The image is not always displayed on click. See the following GIF animations below for understanding:
This is my sourcecoude:
const initialState = {
shouldObserve: false,
};
function reducer(state, action) {
switch (action.type) {
case "observe":
return { shouldObserve: true };
case "reset":
return initialState;
default:
throw new Error();
}
}
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
// Prevent calling useEffect at first Render
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
const { shouldObserve } = state;
if (shouldObserve) {
setTimeout(() => {
dispatch({ type: "reset" });
}, TIME_TO_OBSERVE);
}
}, [state]);
GIF animations:
On Mobile (not always showing the image):
Is there any way so that I can guarantee that the image is 100% (always) displayed?
More information about my stack: I use Expo to develop an app for iOS, Android & Web. The output of the Web version is React Native Web, therefore internal React is used here.