React at Preact

Component Best Practices

Before we talk about dumb components, smart components, and pages let's talk about some core principles.

React is all about components, which have two primary methods for receiving, handling, and displaying data: state and props. Understanding the difference between these two concepts is critical to effective use of React for development.

State

State is mutable data. Changing state is the primary driver for re-rendering components, diffing them with the virtual DOM, and updating the browser DOM.

State is maintained by the component itself; it is not passed from component to component. Consider that state can be either completely internal UI-related state (e.g. whether a dropdown is open or closed) or it can be external data-related state (e.g. the name of the currently logged-in user).

Updating the state of a component is achieved by calling this.setState(nextState) from within the component code. When this is called, it replaces existing state keys with the new passed-in state keys (without modifying other existing keys) and triggers the component's render() method.

Props

Props (properties) are values which are generally passed into a component from its parent. In the following JSX component code, both text and onClick are props:

<Button text="click me" onClick={ this.clickHandler } />

Props are immutable (that is, they are treated as immutable) and will either have their default value as defined in getDefaultProps or will have a value passed down by the parent component.

When to use Props vs. State

Components are free to use internal state whenever necessary to provide a good UI experience, but should favor receiving props over directly connecting to external state.

See smart components for more examples.

Code Organization

For now, we are placing both Smart and Dumb components in the same folder app/components and the Pages into app/pages. We may separate smart and dumb in the future.