Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am developing a component in functional components, where there are several other child components in it. There are different states which I am passing to different components. Some of these states have nothing to do with main component. But when I change these states these also causes to re-render of main component and re-render all the child components.

like

const [showSideBar, setShowSideBar] = useState(false);
const [showFloatingButtons, setShowFloatingButtons] = useState(false);
const [showCart, setShowCart] = useState(false);

Now these are passing to different child components like showCart passing to Cart component which setting setShowCart state in main component causes re-rendering of whole screen. Please help if there is any way in functional component to stop re-rendering the main component which obviously cause the re-rendering of while screen while there is not a need to re-render the while screen. I have MainHeader where I have buttons to set these components.

<MainHeader TabClick={(index)=>TabClick(index)} />

I am passing below one to MainHeader to update main component state.

const TabClick = (index) => {
  if (index === 0) {
    setShowSideBar(true)
  } else if (index === 1) {
    setShowFloatingButtons(true)
  } else if (index === 2) {
    setShowCart(true)
  }
};
question from:https://stackoverflow.com/questions/66050457/react-how-to-stop-rerendering-component-on-some-specific-state-change

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try using Memo to prevent functional components from rendering unnecessarily. https://pt-br.reactjs.org/docs/react-api.html#reactmemo

Or shouldComponentUpdate for classes https://pt-br.reactjs.org/docs/react-component.html

EDIT: Return true in areEqual if you want the component to rerender

function MyComponent(props) {

}
function areEqual(prevProps, nextProps) {

}
export default React.memo(MyComponent, areEqual);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...