Sephy
Sephy

Reputation: 50392

How to ignore a property update of the state in ReactJs?

I know that you can use shouldComponentUpdate to decide if render should be called or not. Citing the docs :

By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, but if you are careful to always treat state as immutable and to read only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.

But my trouble is a bit different. I calculate a value in componentDidUpdate because a need a first render to be able to do my computation, and i'd like to store this value on the state to be able to use it later on in the render function, but I dont want to trigger a render when I modify it.

How would you do it ? Is this the proper way to go ? Should I store this value somewhere else ? Directly on the this ?

Upvotes: 5

Views: 3320

Answers (1)

Andreyco
Andreyco

Reputation: 22862

Compute your state before component is actually updated.

componentWillUpdate(nextProps, nextState) {
  nextState.value = nextProps.a + nextProps.b;
}

Your component will get computed value with other changes and will update only one time.

Upvotes: 3

Related Questions