Tom
Tom

Reputation: 1468

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.

Upvotes: 2

Views: 2015

Answers (2)

Mahmood Bagheri
Mahmood Bagheri

Reputation: 222

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>;
});

Upvotes: 2

divyraj
divyraj

Reputation: 191

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

Upvotes: 2

Related Questions