2

I have a Class React component, that uses a functional Hook component if the browser pathName is /exp

When the page loads up, my app component changes is state about 3-4 times,

How can I prevent the Example hook from remounting if the prop has not changed ?

import React, { useState } from 'react'; function Example() { console.log("i mounted") } 

__

export default class App extends Component { state={key:"value"} <--------------------------------------MAIN APP STATE CHANGES 3 times componentDidMount(){ //I change App state 3 times with conditional code } render() { return ( <Router> <Switch> <Route path="/exp"> <Example prop="I have not changed" /> <-----------------PREVENT MULTIPLE MOUNTINGS </Route> </Switch> </Router> ) } 
2
  • Consider to use export default React.memo(App) Commented Nov 1, 2020 at 16:40
  • Well App is not a functional component, I dont think I can use React.memo there Commented Nov 1, 2020 at 16:43

1 Answer 1

4
const Chat = React.memo(props => { console.log("Greeting Comp render"); return <></> }); export default Chat //This worked for me 

You can use React.memo and render when prop change

function MyComponent(props) { /* render using props */ } function areEqual(prevProps, nextProps) { /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */ } export default React.memo(MyComponent, areEqual); 

or

shouldcomponentupdate if class component

shouldComponentUpdate(nextProps, nextState) 

Note: This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

Sign up to request clarification or add additional context in comments.

3 Comments

I'll have to read the docs, I did a copy paste and MyComponent is still rendering multiple times
const Chat = React.memo(props => { console.log("Greeting Comp render"); return <></> }); export default Chat This worked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.