I understand that in React state should only contain data which may
change and cannot be computed from elsewhere,
I think there is no need to store something that cannot change in a variable at all (use constants for that). And if something can be computed from elsewhere, you might wrap calculation into a function and call it when you need. So, this applies not to React component's state, but to a more wider scope of problems.
however what about simple UI state that is not determined from any
particular data and does not need to persist long-term?
My opinion is that React component's state should contain everything, that affects the presentation of your component at any point in time.
For example, I have a mobile menu which is collapsible on small
screens via CSS. The initial state of this menu is closed, and a
simple onClick handler is attached to the toggle button.
Your onClick
should do one of the following:
Long way: Send a message via an action to a datastore about user action. Datastore will consider the situation (can user click the item or not, for example) and will send state information into a components (using action or by trigger
ing datastore (in Reflux). Component will modify its state using datastore information by calling setState
(and rerendering afterwards).
Short way: call setState directly from your onClick
handler.
In both cases component's state
should definitely include the collapsed
field (or whatever other field, affecting how the component is rendered).
Another important consideration: React philosophy (my point of view) disregards DOM modifications outside render()
calls. Of course you can use jQuery from render() to modify components, but... this may soon cause problems if jQuery starts modifying something, that was just rendered by React.
It is always better not to touch DOM rendered by React outside render()
.