V
V
Viktor2019-11-09 22:59:51
React
Viktor, 2019-11-09 22:59:51

How to avoid re-rendering?

There is such a code:
5dc71a0c6ef8b015261388.png
When mounting, 4 renderings occur,
5dc71aaf9c2d0727009425.png
please explain why and how to get rid of this. thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew Hecc, 2019-11-09
@Hecc

Try wrapping the function in React.memo()
Maybe it will get rid of unnecessary redraws if they occur with the same props

A
akyl-kb, 2019-11-09
@akyl-kb

UPD:
1 option using hooks:

const App = (...) => {
    ...
    const memorizedMessagesChecked = useMemo(() => <MessagesChechked {...props} />, [props.match.params.id])
    return (
        <SomeComponents />
        {memorizedMessagesChecked}
    )
}

Option 2 to use the component class:
class MessagesChechked extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.match.params.id === this.props.match.params.id) {
            return false
        }
        return true
    }
    ...
}

3 option wrap in React.memo
const MessagesChechked = (...) => {
   ...
}

const isEqual = (prevProps, nextProps) => {
   return prevProps.match.params.id !== nextProps.match.params.id
}

export default React.memo(MessagesChechked, isEqual)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question