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

178
Vistas
React - call function in child component if parent state changes

I've got an invisible fullscreen event processing component that catches and processes all mouse events. On certain events I want to call a particular function in a child component. I created a state variable in the parent component. I am listening with use effect in the child component if there are some changes to the state variable in the parent component. However the effect hook is being called to often. Is there a better way of doing this? In particular I want to set drawing=true on mouse down and drawing=false on mouse up. If drawing transitions from true to false I want so save something in the database. Therefore it's important that the function in useState is being called only once.

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

0

I have these two possible solutions.

  1. If you want useEffect not to be called in the first render, you have to use a custom hook, probably called useUpdateEffect. Here is a usage guide from react-use package
  1. use useImperativeHandle to run a function in child from parent. example:
import React, { forwardRef, useRef } from 'react';

export default function Parent() {
    const ref = useRef<Ref>(null!);

    const handleCallFunction = (): void => ref?.current?.functionInChild();

    return (
        <div>
            <button onClick={handleCallFunction}>
                call a function in child from parent
            </button>
            <Child ref={ref} />
        </div>
    );
}

type Ref = {
    functionInChild: () => void;
};

type Props = {};

const Child = forwardRef<Ref, Props>((props, ref) => {
    const functionInChild = () => {
        console.log('called from parent');
    };

    React.useImperativeHandle(ref, () => ({ functionInChild }));

    return <div>Child!</div>;
});

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to put this in your code

useEffect(()=>{
   /*Query logic*/
console.log('i fire once');},[your_variable]);

you_variable which you want to change when this variable changes his value

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