facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
229.65k stars 47.02k forks source link

Some guidance on `state` storage, for performance reasons #4211

Closed benhowdle89 closed 9 years ago

benhowdle89 commented 9 years ago

I have sandboxed a contrived example of my use-case:

http://react.jsbin.com/peseveluxi/edit?js,output

My rough use-case is a chat app, where each character typed is stored as a Backbone Model in a Backbone Collection (for filtering purposes, etc...). When a new character is typed, I add a new Model to the Collection and then use setState to set a value property to the Collection itself. In the render, I then map over the value property and output the text.

My specific question is, is this best way to get the best way out of React, in terms of storing all the typed text into the value state object? Or is there a better way (to avoid re-rendering the whole block of text when typing a new single character)

jimfb commented 9 years ago

Your approach seems reasonable to me, but I defer to @spicyj and others for a more authoritative answer.

In general, when perf starts becoming an issue, we recommend switching to immutable datastructures and using shouldComponentUpdate to avoid unnecessary rerenders. If that isn't enough and you're trying to super-optimize a particular component, and you're able to track "changes" to your data, you can cache the ReactElements and perform imperative mutations to keep your ReactElements synchronized with your data (obviously this defeats the main advantages of using React, so it's not the recommended solution except in cases where you need to squeeze every last ounce of performance out of a component).

In the future, this type of question is probably better suited for a place like StackOverflow, as we use github issues for tracking bugs in React. Since this is not a bug in React, I'm going to close this issue for tracking purposes, but feel free to continue the discussion here.