Delay in redirection causes a temporary display of incorrect components

Viewed 20

Experiencing issues where I want to redirect the page based on a logic.

So if I redirect, should just go to the page I am redirecting and not show the components within MyComponent.

The redirect does occur but there is a delay like 1 - 2 second.
During this period, there is a display of the component when it shouldn't.
Is there a way to prevent this and just redirect?

Note: This component has been minimised to focus on the issue. Actual component has a lot more going on in there.

The issue can be observed in this minimal project. https://github.com/kvaithin/react-routing-issue

const MyComponent = () => {
  const [data, setData] = useState();

  // just a temp call to emulate getting data
  useEffect(() => {
    fetch("https://api.npms.io/v2/search?q=react")
      .then((response) => response.json())
      .then((d) => setData(d));
  }, []);

  // i want this redirect to happen without seeing the text below.
  useEffect(() => {
    const redirect = true;
    if (redirect) {
      // some other logic that will determine if redirect = true
      window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
    }
  }, []);

  return (
    <div>
      I should never reach here cos of the redirect But I still see this text briefly for a second
      or 2 before redirecting.
      {/* other components inside here  */}
    </div>
  );
};

export default MyComponent;
1 Answers

"The function passed to useEffect will run after the render is committed to the screen". If you want to prevent the content to be shown before you excute your logic, you could use a checking state like so:

const MyComponent = () => {
  const [data, setData] = useState();
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    fetch("https://api.npms.io/v2/search?q=react")
      .then((response) => response.json())
      .then((d) => setData(d));
  }, []);

  useEffect(() => {
    const redirect = true;
    if (redirect) {
      setChecking(false);
      window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
    }
  }, []);

  if (checking) return null; // or a loading message or component

  return (
    <div>
      I should never reach here cos of the redirect But I still see this text briefly for a second
      or 2 before redirecting.
    </div>
  );
};

export default MyComponent;
Related