Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I invoke a callback within a React function component?

This is the code I have working right now from this answer, whose comments suggested using window.history. It works, but I’d prefer to go back correctly, using React router v6.

import {useNavigate} from "react-router-dom";
import Cookies from "universal-cookie"; 

function Foo() {
  const navigate = useNavigate();
  const cookies = new Cookies();

  if (cookies.get('foo') === 'bar') {
    window.history.go(-1);
    // () => navigate(-1); // this does not work
  }
  return (
    <div />
  )
}

You can see commented out what I wanted to do, but that’s not legal I think. And if I just use navigate(-1) it doesn’t work, like the original question I linked.

So is there a way to use navigate inside Foo?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

() => navigate(-1); // this does not work

This defines a function which will call navigate(-1) when it is called.

You never call it.


The dirty approach is to simply not wrap it in a function, but the main render function of a component shouldn’t have side effects.

Wrap it in an effect hook instead.

const Foo = () => {
  const navigate = useNavigate();
  const cookies = new Cookies();

  const foo = cookies.get('foo');

  useEffect(() => {
      if (foo === 'bar') {
          navigate(-1);
      }
  }, [foo, navigate]);

  return (
    <div />
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading