Components let you split the UI into independent, reusable pieces, and think about each piece in isolation [*]
A valid React component accepts at least a single props object argument with data and returns a React element.
Functional Components
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
Class Components
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Rendering a Component
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } const element = <Welcome name="Sara" />; ReactDOM.render( element, document.getElementById('root') );
Composing Components
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div> ); } ReactDOM.render( <App />, document.getElementById('root') );
This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
React Rule on Props
function sum_pure(a, b) { return a + b; } function withdraw_impure(account, amount) { account.total -= amount; }
Class Properties - defaultProps
class CustomButton extends React.Component { // ... } CustomButton.defaultProps = { color: 'blue' };
class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
React.Component Lifecycle - Mounting
React.Component Lifecycle - Mounting - constructor
constructor(props) { super(props); this.state = { color: props.initialColor }; }
When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. It's okay to initialize state based on props. This effectively "forks" the props and sets the state with the initial props.
React.Component Lifecycle - Mounting - componentWillMount
is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method. This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.
React.Component Lifecycle - Mounting - render
The render() method is required. The returning element can be either a representation of a native DOM component, such as <div />, or another composite component that you've defined yourself. You can also return null or false to indicate that you don't want anything rendered. When returning null or false, ReactDOM.findDOMNode(this) will return null. The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.
React.Component Lifecycle - Mounting - componentDidMount
is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
React.Component Lifecycle - Updating
React.Component Lifecycle - Updating - componentWillReceiveProps
If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method. Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.
React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update. Calling this.setState generally doesn't trigger componentWillReceiveProps.
React.Component Lifecycle - Updating - shouldComponentUpdate
Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
It is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.
Returning false does not prevent child components from re-rendering when their state changes.
Currently, if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked. Note that in the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.
If you determine a specific component is slow after profiling, you may change it to inherit from React.PureComponent which implements shouldComponentUpdate() with a shallow prop and state comparison. If you are confident you want to write it by hand, you may compare this.props with nextProps and this.state with nextState and return false to tell React the update can be skipped.
React.Component Lifecycle - Updating - componentWillUpdate
It is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.
It will not be invoked if shouldComponentUpdate() returns false.
React.Component Lifecycle - Updating - componentDidUpdate
This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
It will not be invoked if shouldComponentUpdate() returns false.
React.Component Lifecycle - Unmounting
React.Component - setState
This is the primary method you use to update the user interface in response to event handlers and server responses. Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. It may batch or defer the update until later. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.
setState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.
If you need to set the state based on the previous state, read about the updater argument below.
prevState is a reference to the previous state. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from prevState and props.
React.Component - setState
this.setState((prevState, props) => { return {counter: prevState.counter + props.step}; }); this.setState(function(prevState, props) { return { counter: prevState.counter + props.increment }; }); this.setState({quantity: 2})
React.Component - forceUpdate
Let's look at a real implemented React Component in [here].
- like: const element = <h1>Hello, world</h1>
React Only Updates What's Necessary Using Virtual DOM
function tick() { const element = ( <div> <h1>Hello, world!</h1> <h2>It is {new Date().toLocaleTimeString()}.</h2> </div> ); ReactDOM.render( element, document.getElementById('root') ); } setInterval(tick, 1000);
DOM manipulation is the heart of the modern, interactive web. Unfortunately, it is also a lot slower than most JavaScript operations. This slowness is made worse by the fact that most JavaScript frameworks update the DOM much more than they have to. As an example, let's say that you have a list that contains ten items. You check off the first item. Most JavaScript frameworks would rebuild the entire list. That's ten times more work than necessary! Only one item changed, but the remaining nine get rebuilt exactly how they were before. Rebuilding a list is no big deal to a web browser, but modern websites can use huge amounts of DOM manipulation. Inefficient updating has become a serious problem. To address this problem, the people at React popularized something called the virtual DOM.
Here is what happens in updating the DOM in React:
Space | Forward |
---|---|
Right, Down, Page Down | Next slide |
Left, Up, Page Up | Previous slide |
P | Open presenter console |
H | Toggle this help |