Dariusz Legizynski
Dariusz Legizynski

Reputation: 386

React: passing data between sibling without causing a rerender

I have the following problem: I got an App (A) and a lot of children (B, C, etc). Now I would like to pass a value from B to C but without any rerender of the whole App. How is this possible?

A (Parent)
    |---- B (Child)
    |---- C (Child)
    |---- D (Child)
    |---- E (Child)
    |---- F (Child)

I tried to use useContext or a simple callback but in each case the state is hold in A, which, by change makes my whole App to rerender. Any Idea on how to make ii in a proper way?

Upvotes: 0

Views: 1143

Answers (3)

Rakib Uddin
Rakib Uddin

Reputation: 876

You can use

shouldComponentUpdate

to avoid this type of scenario. It works for both props and state.

shouldComponentUpdate(nextProps, nextState) {
 return this.props.somevalue != nextProps.somevalue;
}

Check if there is any new props passed to the child. If not then the component wont re-render. But avoid using too many children and come up with a better design structure.

Edit:

You can use

PureComponent

as it implements shouldComponentUpdate by default. As mentioned in the doc:

React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

Upvotes: 2

SaimumIslam27
SaimumIslam27

Reputation: 1188

You can use React.memo(component) This is saved your component from unusual renders. read this one https://reactjs.org/docs/hooks-reference.html#usememo

Upvotes: 1

Yves Kipondo
Yves Kipondo

Reputation: 5603

The default behavior in React is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. But when you want to block the re-render of component when the state change and some value from state are passed to child component as props you can take advantage of shouldComponentUpdate

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Lean more here

To block the re-render you should should perform a check in the shouldComponentUpdate to ensure that the previous props and the current one aren't the same. If they are the same. you block the re-render by return false and if they are different you return true which will trigger the re-render.

Or you can use memo

Upvotes: 2

Related Questions