Three Tips For Optimizing Your react-redux Applications
Tip #1: When subscribing a component to the store, only subscribe to the specific data it needs
// Before
let selectedId = useSelector ( state => state . list . selectedId ) ;
let isSelected = props . id === selectedId ;
// After
let isSelected = useSelector ( state => state . list . selectedId === props ) ;
Being specific in your subscriptions will help keep your components from re-rendering unecessarily.
Don't be afraid to write simple logic inside your of you selector functions.
Think about what the component really needs.
Does it need an id, or does it just need a boolean?
Tip #2: Avoid subscribing to objects in your store
// Before
let { list, name} = useSelector ( state => state . list ) ;
// After
let list = useSelector ( state => state . list . list ) ;
let name = useSelector ( state => state . list . name ) ;
When using the useSelector()
hook, returning an object will always cause your component to re-render.
Tip #3: Subscribe more components (instead of passing props)
// Before
function Parent ( ) {
let name = useSelector ( state => state . list . name ) ;
return (
< >
< FavoriteChild name = { name } />
< OtherChild />
</ >
)
}
function FavoriteChild ( props ) {
return < h2 > { props . name } </ h2 > ;
}
FavoriteChild
and OtherChild
will re-render every time name
changes.
//After
function Parent ( ) {
return (
< >
< FavoriteChild />
< OtherChild />
</ >
)
}
function FavoriteChild ( props ) {
let name = useSeletor ( state => state . list . name ) ;
return < h1 > { name } </ h1 > ;
}
When name
changes, only FavoriteChild
will re-render.
Keep the subscription close to where the data is being used.
Don't be afraid to subscribe more components instead of leveraging what's already subscribed.