Reputation: 694
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>
)
}
Upvotes: 2
Views: 2999
Reputation: 1454
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.
Upvotes: 4