React parent to child props passing without rerender

726 Views Asked by At

I have a button on my parent component and a third-party form in a child component. When the user clicks the button, the save function in the child component should run. This is my plan.

Method 1 I tried: 1.Created a variable on parent called save. 2. When button is clicked, save becomes true 3. Save is passed down to the child as props 4. Child contains a useEffect() which listens to changes in props.save 5. If props.save is true, save function of child component runs

Method 2 I tried:

  1. Instead of passing props, I created a react-redux store.
  2. The store contains save variable which is false by default
  3. When button is clicked, save in redux becomes true
  4. I use useSelector() hook to listen to the save variable change, inside the child component
  5. UseEffect is used to run the save() function when the value change is detected

What happens with both methods is that I am losing the data in my child component because the variable change in the parent causes a page refresh. Therefore I want to pass the data down to the child, without causing rerenders. What are the options I have?

Thanks in advance

1

There are 1 best solutions below

0
On

Thanks to @Shyam, I could finally solve this issue!

My assumption that useState and props cause render was correct. And as @Shyam suggested, there is no direct way to avoid it.

I am using react-editor-js in my project and that's what caused the issue

  <EditorJs
    instanceRef={()=>{//code to save the reference as state variable}}
    enableReInitialize
    data={{}}
    tools={EDITOR_JS_TOOLS}
  />

The reason for state loss was that my instanceRef was being reassigned every time the component renders.

This reassignment can be prevented by wrapping the method to save the reference as a state variable with useCallback()