In react functional component, stop child re-rendering when parent function is called from child component

Viewed 78

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

1 Answers

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

You don't need the useCallback hook to do the functionality you are looking for. So skip that.

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

Related