Reputation: 32247
Scenario
Depending on the data coming into props I may want my component to render but I also may NOT want my component to rerender.
Code
Currently I'm using if(!props.data) return null
but this merely sends back a blank component.
Question
How can I forfeit the render so that my current dom element stays unchanged, leaving the last rendered content intact? I'm wanting my component only update when props.data
has a truthy value.
Upvotes: 0
Views: 27
Reputation: 16354
You can store the data received in a local state and only update it if props.data
changes and has a truthy value like this:
import React, {useEffect, useState} from 'react';
const MyComponent = ({data}) => {
const [localData, setLocalData] = useState(data);
useEffect(() => {
if (data) setLocalData(data);
}, [data]);
return (
<div>{localData}</div>
);
};
But note that this has a little bit of a design smell. Why does your component receive new props in the first place if it shouldn't update. The correct place to hold that state may be in a component further up the tree.
Upvotes: 1
Reputation: 609
The simple way is to try using conditional rendering of the component if the data
is present in the parent instead of checking the props within the component.
function ParentComponent(props) {
const data = <your custom data>;
if(data) {
return <ChildComponent data={data} />;
}
}
Upvotes: 0