Home > Back-end >  in react functional component, stop child re-rendering when parent function call from child componen
in react functional component, stop child re-rendering when parent function call from child componen

Time:07-08

in react I have 2 functional component, I want to call parent's function in child component on button click which update parent state. on this function invoke my child component is re-render.so I want Stop this re-rendering, i trying solve it as follow but not working

app.js

import React, { useState, useCallback } from "react"; 
import Child from "./child"; 
export default function App() 
{   let [show, setShow] = useState(false);   
    console.log("App Re-render:", show);   
    const setMyState = useCallback(() => {
         setShow(!show);   
    });   

    return (
        <div className="App">
          <h1>Parent Component</h1>
          <h2>----------------------------------</h2>
          <Child func={setMyState}></Child>
        </div>   
    ); 
}

child.js

import React, { memo } from "react";
function Child({ func }) {
  console.log("Child re-render");
  return (
    <div>
      <p>Child Component</p>
      <button onClick={func}>Call Parent Method </button>
    </div>
  );
}
export default memo(Child);

this "func" function should call multiple time. please help me to solve this problem

CodePudding user response:

The code you posted looks good. Do you have more code that isn't posted? Can you try to reproduce in an example?

I have done the same thing here and it works: https://codesandbox.io/s/gallant-hellman-60lw3d?file=/src/App.js

CodePudding user response:

React won't rerender the component if there is no use of the state in the child component that was been updated by the setState function this mechanism has been calculated in the virtual DOM.

if you want it to be rendered pass and use the show state

import React, { memo } from "react";
function Child({ func, show }) {
  console.log("Child re-render");
  if (!show) return <></>;

  return (
    <div>
      <p>Child Component</p>
      <button onClick={func}>Call Parent Method </button>
    </div>
  );
}
export default memo(Child);

Another possible issue is the miss of useCallback dependency array. see Poku example.

see more about useCallback.

  • Related