What Is Component State?

Most components should simply take in props and render. But, components also offer state, and it is used to store information about the component that can change over time. Typically the change comes as a result of user events or system events (i.e., as a response to user input, a server request or the passage of time).

According to the React documentation state should:

Contain data that a component's event handlers may change to trigger a UI update. In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in this.state. Inside of render() simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you.

Things to keep in mind about React component state:

  1. If a component has a state a default state should be providing 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. You inform a component of a state change by using this.setState() to set a new state.
  4. A state change merges new data with old data that is already contained in the state (i.e., this.state)
  5. A state change, internally deals with calling re-renders. You should never have to call this.render() directly.
  6. 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 ""