Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

() => 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 />
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda