How to stop re render child component when any state changed in react js?

為{幸葍}努か 提交于 2021-02-20 19:06:31

问题


I have a parent componenet, Inside this I have included a child component with props. but When any state is changed in parent component (that doesn't related to child component) then child component re-render. I don't want this re render on every state change. Can we stop?

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Child from "./child";
import "./styles.css";

function App() {
  const [any_state, setAnyState] = useState(false);

  const handleClick = () => {
    setAnyState(!any_state);
  };
  return (
    <div className="App">
      Parent Page ({any_state ? "true" : "false"})
      <br />
      <button onClick={handleClick}>Click me</button>
      <Child data={"any data"} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

child.js

import React from "react";

function Child(props) {
  console.log("child component");
  return <div className="App">child Page</div>;
}

export default Child;

https://codesandbox.io/s/clever-oskar-fpxm3?fontsize=14

I don't want "child component" to be displayed in console on every state change.


回答1:


You want to use React.memo for this. Read more here.

This will prevent re-renders when props did not change.

Instead of export default Child; use export default React.memo(Child); in your child.js.

import React from "react";

function Child(props) {
  console.log("child component");
  return <div className="App">child Page</div>;
}

export default React.memo(Child);



回答2:


You gonna have to set up a Redux state

Or you just isolate the React Hook useState, make a good component destructuring :)

App.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Child from "./child";
import Parent from "./parent"; // <--------- HERE
import "./styles.css";

function App() {
  return (
    <div className="App">
      <Parent />
      <Child data={"any data"} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

parent.js

function Parent() {
  const [any_state, setAnyState] = useState(false);

  const handleClick = () => {
    setAnyState(!any_state);
  };
  return (
    <>
      Parent Page ({any_state ? "true" : "false"})
      <br />
      <button onClick={handleClick}>Click me</button>
    </>
  );
}



来源:https://stackoverflow.com/questions/58219732/how-to-stop-re-render-child-component-when-any-state-changed-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!