React
Terms & Concepts
- Components
- Props
- Props are Read-Only (Should be written as Pure Functions)
- State
- State is similar to props, but it is private and fully controlled by the component.
- Lifecycle
- Immutability
- Synthetic Events
- Redux
- store
- actions
- reducers
- "The Data Flows Down"
Components
Component
Presentational Components | Container Components | |
---|---|---|
Purpose | How things look (markup, styles) | How things work (data fetching, state updates) |
Aware of Redux | No | Yes |
To read data | Read data from props | Subscribe to Redux state |
To change data | Invoke callbacks from props | Dispatch Redux actions |
Are written | By hand | Usually generated by React Redux |
usual format | function | class |
Props
- All React components must act like pure functions with respect to their props.
State
- Do Not Modify State Directly
- State Updates May Be Asynchronous
- State Updates are Merged
- When you call
setState()
, React merges the object you provide into the current state.
- When you call
Lifecycle
componentDidMount()
componentWillUnmount()
Event Handling
This binding is necessary to make
this
work in the callbackconstructor(props) { super(props); this.state = {isToggleOn: true}; this.handleClick = this.handleClick.bind(this); }
you can use property initializers to correctly bind callbacks
handleClick = () => { console.log('this is:', this); }
- If you aren't using property initializer syntax, you can use an arrow function in the callback
- This syntax ensures
this
is bound within handleClickrender() { return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); }
Conditional Rendering
- Element Variables
- You can use variables to store elements.
- This can help you conditionally render a part of the component while the rest of the output doesn't change.
- Inline If with Logical && Operator
- Inline If-Else with Conditional Operator
- Preventing Component from Rendering
Lists & Keys
- The
map()
method creates a new array with the results of calling a provided function on every element in the calling array. - Rendering Multiple Components
- Keys
- Keys help React identify which items have changed, are added, or are removed.
- Keys should be given to the elements inside the array to give the elements a stable identity:
- Keys help React identify which items have changed, are added, or are removed.
- Keys should be given to the elements inside the array to give the elements a stable identity
Misc.
- Components must return a single root element.
- Functional Components: Accept a single "props" object argument with data and return a React element.
- Class Components:
class Element extends React.Component {}
constructor
method whereinsuper()
is called
Methods
React
React.Component
this.setState()
e.preventDefault();
ReactDOM
ReactDOM.render(element, target);
Redux
createStore()
store.getState()
store.subscribe()
store.dispatch()