Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 526
Sephy Avatar asked Oct 18 '22 10:10

Sephy


1 Answers

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.

like image 90
Andreyco Avatar answered Oct 21 '22 04:10

Andreyco