If a component uses some data from a custom hook and if the custom hook also contains data (local/global) which is not consumed by the above component, then the component re-renders even when the non-dependent data changes (references for non-primitive types). Is there a way to prevent this?
Example code:
useTest.hook.js
export default function useTest() {
const {
consumedData, nonConsumedData
} = useSelector(state => state.Data);
return {
consumedData,
nonConsumedData
}
}
Component.js
export default function Component() {
const {consumedData} = useTest();
return <div>{consumedData}</div>;
}
Here Component re-renders when nonConsumedData changes ( or even when state.Data changes ). nonConsumedData might be consumed by some other component. Is there a way to stop the re-render in such cases?
You can use memoization to avoid re-rendering components (if re-rendering affects performances).
With function based components, just use React.memo()
const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});
More information here: https://reactjs.org/docs/react-api.html#reactmemo