layout: 2017/sheet
ads: true
tags: [Featured]
-updated: 2018-10-04
+updated: 2020-07-05
weight: -10
keywords:
- React.Component
}
```
-
{: data-line="5,6,7,8,9,10"}
Nest components to separate concerns.
```jsx
class Hello extends Component {
- state = { visible: true }
- }
+ state = { visible: true }
}
```
-
{: data-line="2"}
See: [Setting the default state](https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state)
### Mounting
-| Method | Description |
-| --- | --- |
-| `constructor` _(props)_ | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor) |
-| `componentWillMount()` | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount) |
-| `render()` | Render [#](https://reactjs.org/docs/react-component.html#render) |
-| `componentDidMount()` | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
-| --- | --- |
-| `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount) |
-| --- | --- |
-| `componentDidCatch()` | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) |
+| Method | Description |
+| ------------------------ | ---------------------------------------------------------------------------------------------------- |
+| `constructor` _(props)_ | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor) |
+| `componentWillMount()` | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount) |
+| `render()` | Render [#](https://reactjs.org/docs/react-component.html#render) |
+| `componentDidMount()` | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
+| --- | --- |
+| `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount) |
+| --- | --- |
+| `componentDidCatch()` | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) |
Set initial the state on `constructor()`.
Add DOM event handlers, timers (etc) on `componentDidMount()`, then remove them on `componentWillUnmount()`.
### Updating
-| Method | Description |
-| --- | --- |
-| `componentDidUpdate` *(prevProps, prevState, snapshot)* | Use `setState()` here, but remember to compare props |
-| `shouldComponentUpdate` *(newProps, newState)* | Skips `render()` if returns false |
-| `render()` | Render |
-| `componentDidUpdate` *(prevProps, prevState)* | Operate on the DOM here |
+| Method | Description |
+| ------------------------------------------------------- | ---------------------------------------------------- |
+| `componentDidUpdate` _(prevProps, prevState, snapshot)_ | Use `setState()` here, but remember to compare props |
+| `shouldComponentUpdate` _(newProps, newState)_ | Skips `render()` if returns false |
+| `render()` | Render |
+| `componentDidUpdate` _(prevProps, prevState)_ | Operate on the DOM here |
Called when parents change properties and `.setState()`. These are not called for initial renders.
See: [Component specs](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)
+Hooks (New)
+-----------
+{: .-two-column}
+
+### State Hook
+
+```jsx
+import React, { useState } from 'react';
+
+function Example() {
+ // Declare a new state variable, which we'll call "count"
+ const [count, setCount] = useState(0);
+
+ return (
+ <div>
+ <p>You clicked {count} times</p>
+ <button onClick={() => setCount(count + 1)}>
+ Click me
+ </button>
+ </div>
+ );
+}
+```
+{: data-line="5,10"}
+
+Hooks are a new addition in React 16.8.
+
+See: [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
+
+### Declaring multiple state variables
+
+```jsx
+function ExampleWithManyStates() {
+ // Declare multiple state variables!
+ const [age, setAge] = useState(42);
+ const [fruit, setFruit] = useState('banana');
+ const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
+ // ...
+}
+```
+
+### Effect hook
+
+```jsx
+import React, { useState, useEffect } from 'react';
+
+function Example() {
+ const [count, setCount] = useState(0);
+
+ // Similar to componentDidMount and componentDidUpdate:
+ useEffect(() => {
+ // Update the document title using the browser API
+ document.title = `You clicked ${count} times`;
+ }, [count]);
+
+ return (
+ <div>
+ <p>You clicked {count} times</p>
+ <button onClick={() => setCount(count + 1)}>
+ Click me
+ </button>
+ </div>
+ );
+}
+```
+{: data-line="6,7,8,9,10"}
+
+If you’re familiar with React class lifecycle methods, you can think of `useEffect` Hook as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined.
+
+By default, React runs the effects after every render — including the first render.
+
+### Building your own hooks
+
+#### Define FriendStatus
+```jsx
+import React, { useState, useEffect } from 'react';
+
+function FriendStatus(props) {
+ const [isOnline, setIsOnline] = useState(null);
+
+ useEffect(() => {
+ function handleStatusChange(status) {
+ setIsOnline(status.isOnline);
+ }
+
+ ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
+ return () => {
+ ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
+ };
+ }, [props.friend.id]);
+
+ if (isOnline === null) {
+ return 'Loading...';
+ }
+ return isOnline ? 'Online' : 'Offline';
+}
+```
+{: data-line="11,12,13,14"}
+
+Effects may also optionally specify how to “clean up” after them by returning a function.
+
+#### Use FriendStatus
+
+```jsx
+function FriendStatus(props) {
+ const isOnline = useFriendStatus(props.friend.id);
+
+ if (isOnline === null) {
+ return 'Loading...';
+ }
+ return isOnline ? 'Online' : 'Offline';
+}
+```
+{: data-line="2"}
+
+See: [Building Your Own Hooks](https://reactjs.org/docs/hooks-custom.html)
+
+### Hooks API Reference
+
+Also see: [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html)
+
+#### Basic Hooks
+
+| Hook | Description |
+| ---------------------------- | ----------------------------------------- |
+| `useState`_(initialState)_ | |
+| `useEffect`_(() => { ... })_ | |
+| `useContext`_(MyContext)_ | value returned from `React.createContext` |
+
+Full details: [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)
+
+#### Additional Hooks
+
+| Hook | Description |
+| -------------------------------------------- | ---------------------------------------------------------------------------- |
+| `useReducer`_(reducer, initialArg, init)_ | |
+| `useCallback`_(() => { ... })_ | |
+| `useMemo`_(() => { ... })_ | |
+| `useRef`_(initialValue)_ | |
+| `useImperativeHandle`_(ref, () => { ... })_ | |
+| `useLayoutEffect` | identical to `useEffect`, but it fires synchronously after all DOM mutations |
+| `useDebugValue`_(value)_ | display a label for custom hooks in React DevTools |
+
+Full details: [Additional Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)
+
DOM nodes
---------
{: .-two-column}
#### Fragments
```js
render () {
- // Fragments don't require keys!
return (
<Fragment>
<li>First item</li>
See: [Typechecking with PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html)
-| `any` | Anything |
+| Key | Description |
+| ----- | ----------- |
+| `any` | Anything |
#### Basic
-| `string` | |
-| `number` | |
-| `func` | Function |
-| `bool` | True or false |
+| Key | Description |
+| -------- | ------------- |
+| `string` | |
+| `number` | |
+| `func` | Function |
+| `bool` | True or false |
#### Enum
-| `oneOf`_(any)_ | Enum types |
-| `oneOfType`_(type array)_ | Union |
+| Key | Description |
+| ------------------------- | ----------- |
+| `oneOf`_(any)_ | Enum types |
+| `oneOfType`_(type array)_ | Union |
#### Array
-| `array` | |
-| `arrayOf`_(...)_ | |
+| Key | Description |
+| ---------------- | ----------- |
+| `array` | |
+| `arrayOf`_(...)_ | |
#### Object
-| `object` | |
-| `objectOf`_(...)_ | Object with values of a certain type |
-| `instanceOf`_(...)_ | Instance of a class |
-| `shape`_(...)_ | |
+| Key | Description |
+| ------------------- | ------------------------------------ |
+| `object` | |
+| `objectOf`_(...)_ | Object with values of a certain type |
+| `instanceOf`_(...)_ | Instance of a class |
+| `shape`_(...)_ | |
#### Elements
-| `element` | React element |
-| `node` | DOM node |
+| Key | Description |
+| --------- | ------------- |
+| `element` | React element |
+| `node` | DOM node |
#### Required
-| `(···).isRequired` | Required |
+| Key | Description |
+| ------------------ | ----------- |
+| `(···).isRequired` | Required |
### Basic types