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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I invoke a callback within a React function component? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

() => 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 />
  );
};
We are here to answer your question about How can I invoke a callback within a React function component? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji