Optimizing Component Renders with Redux v5.0.0
Explores the use of React.memo and Redux hooks to prevent unnecessary component re-renders, demonstrating the benefits of Redux v5.0.0's optimized subscription management.
import React, { memo } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
// Custom selector using Reselect for memoization
import { selectSpecificData } from './selectors';
const MyComponent = ({ itemId }) => {
// Use useSelector with shallowEqual to only re-render when the specific data has changed
const itemData = useSelector(state => selectSpecificData(state, itemId), shallowEqual);
return (
<div>{itemData.name}</div>
);
};
// Wrap the component with React.memo to prevent unnecessary renders
export default memo(MyComponent);
This code demonstrates the use of useSelector with shallowEqual for selecting data and only re-rendering when the specific selected data changes. The code fetches specific item data by using the itemId prop passed to MyComponent. Moreover, React.memo wraps the component to avoid re-renders when props haven't changed, which is beneficial for performance with Redux v5.0.0's optimized subscription management.