0

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 Desktop (working well):Desktop

On Mobile (not always showing the image): Mobile

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.

Arbnor
  • 2,190
  • 18
  • 26

1 Answers1

1

Maybe try something like this:

import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [show, setShow] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setShow(false);
    }, 200);
    return () => clearInterval(timer);
  }, [show]);

  return (
    <div className="App">
      <div onClick={() => setShow(true)}>
        {show ? <div>image</div> : <div>start</div>}
      </div>
    </div>
  );
}

here is a code sandbox for testing: https://codesandbox.io/s/nervous-khorana-l903t?file=/src/App.js:0-461

Rob Terrell
  • 2,398
  • 1
  • 14
  • 36