Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!