Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda