Component refreshes when useSelector() value changes

389 Views Asked by At

I have a react-editor-js instance that allows the user to type in some blog content. My form submission button is up on the header and not on the form body. Therefore I use redux to let those button clicks known in my form.

When the button clicks, the isPublishing value in my redux changes. My form is listening to this component using const p = isPublishing(state=> state.test.isPublishing).

Refreshes are evil in this case, as it resets my EditorJs form data. It'd be amazing if I can listen to the changes without page refreshes. How can I achieve it? Thanks in advance!

1

There are 1 best solutions below

0
On

Thanks to @Shyam for the solution.

My assumption that useState and props cause render was correct. 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()