Working with Component State

Working with component state typically involves setting a components default state, accessing the current state, and updating the state.

In the code example below I am creating a <MoodComponent /> that demonstrates the use of getInitialState, this.state.[STATE], and this.setState(). If you click on the component in a web browser (i.e., the face) then it will cycle through the states (i.e., moods) available. Thus, the component has three potential states, tied to the UI, based on clicks from the UI user. Go ahead and click on the face in the results tab below.

source code

Note that the <MoodComponent /> has an initial state of ':|', that is set using getInitialState: function() {return {mood: ':|'};}, which is used in the component when it is first rendered by writing, {this.state.mood}.

To change the state, an event listener is added; in this case a click event (i.e., onClick) on the <span> node that will call the changeMood function. Within this function I use this.setState() to cycle to the next mood based on the current mood/state. After the state is update (i.e., setState() merges the changes) the component will re-render itself and the UI will change.

Things to keep in mind about React component state:

  1. If a component has state, a default state should be provided using getInitialState()
  2. State changes are typically how you start the re-rendering of a component and all sub components (i.e., children, grandchildren, great grand chidlren, etc.).
  3. The only way a component should have its state update should be by using this.setState(). While other ways are possible (i.e. forceUpdate()), they should likely not be used (except maybe when integrating with third-party solutions).
  4. You inform a component of a state change by using this.setState() to set a new state. This will result in re-render of the component and all children components that need re-rendered.
  5. A state change merges new data with old data that is already contained in the state. But this is only a shallow update/merge, it won't do a deep update/merge.
  6. A state change internally deals with calling re-renders. You should never have to call this.render() directly.
  7. The state object should only contain the minimal amount of data needed for the UI. Don't place computed data, other React components, or props in the state object.

results matching ""

    No results matching ""