Facebook React encourages you to separate mutable (state
) and immutable (props
) state:
Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
When the state changes, you are supposed to call setState
to trigger virtual DOM diff, which will cause a real DOM update only when this is needed.
There is a way to trigger DOM update manually by calling forceUpdate
but it is discouraged:
Normally you should try to avoid all uses of
forceUpdate()
and only read fromthis.props
andthis.state
inrender()
. This makes your application much simpler and more efficient.
However, all React+Backbone examples I have seen ignore this advice and store models and collections in props
and call forceUpdate
:
Even React's own example uses forceUpdate
:
Is there a better way, though, and what benefits would it give?
forceUpdate() By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate() .
forceUpdate() It will be called when some data changes other than state or props. It does not skip any lifecycle method. It skips the lifecycle shouldComponentUpdate method.
ReactJS forceUpdate() Method The components in React will re-render only if the state of the component or the props passed to it changes but if we need to re-render the component if some data changes then we will use forceUpdate() method of React.
There are basically two ways in which the data gets handled in React. It gets handled through state and props.
Pete's answer is great.
Backbone models are inherently mutative, which (while not a problem in itself) means that when rerendering, you won't have the old version of the model to compare to. This makes it harder to do intelligent optimizations by defining shouldComponentUpdate
methods in key places on your components. (You also lose out on the ability to easily store old versions of your model for other reasons, like implementing undo.)
Calling forceUpdate
merely skips shouldComponentUpdate
and forces the component to rerender. Note that calling render
is usually cheap, and React will still only touch the DOM if the output of render
has changed, so performance problems here aren't common. However, if you have the choice to use immutable data (including passing around raw model property objects from toJSON()
as Pete suggests), I'd highly recommend it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With