Track React-Redux Redundant Re-Renders With “Why Did You Render” Version 3

@welldone-software/why-did-you-render@^3 tracks redundant Hooks re-renders + React-Redux@^7 uses hooks = Great way to track React-Redux redundant re-renders!

Click here to read about Why Did You Render in general.

whyDidYouRender(React, { include: [/^ConnectFunction$/] })

Possible React-Redux Issues

Bad Action Handling

The following simple reducer and action would cause the state to be re-created on every action dispatched:

const initialState = {a: 'a'}function reducer(state = initialState, action){
return action.payload
}
store.dispatch({payload: {a: 'a'}})console.log(store.getState() === initialState)
// false
const initialState = {a: 'a'}function reducer(state = initialState, action){
if(state.a === action.payload.a){
return state
}

return action.payload
}
store.dispatch({payload: {a: 'a'}})console.log(store.getState() === initialState)
// true

Bad Connection Handling

If the connect function creates an object with new props on it, a re-render would be triggered for every state change in any part of the application:

function SimpleComponent({c}){
console.log('render SimpleComponent!')
return <div>{c.a}</div>
}
const ConnectedComponent = connect(
// Notice how a new "c" is created here on every state change
// Even for state changes that has nothing to do with "a"
// Where state.a === prevState.a
state => ({c: {a: state.a})
)(SimpleComponent)
const initialA = store.getState().a// affects some completely different part of the redux state
store.dispatch({type: 'newX', payload: 'z'})
// "render SimpleComponent!" triggeredconsole.log(store.getState().a === initialA)
// true
function SimpleComponent({a}){
console.log('render SimpleComponent!')
return <div>{a}</div>
}
const ConnectedComponent = connect(
// Notice how the returned "a" prop is always just "a"
state => ({a: state.a})
)(SimpleComponent)
const initialA = store.getState().a// affects some completely different part of the redux state
store.dispatch({type: 'newX', payload: 'z'})
// NOT TRIGGERED: "render SimpleComponent!"console.log(store.getState().a === initialA)
// true

The leading full-stack software solutions company. Creating amazing frontends and rock-solid backends using top-notch technologies and practices. Visit us at https://welldone.software/