React Core Library
react is the core React library.react-dom is used for DOM-related operations.
Class Component Inheritance
- Class components in React inherit from
React.Component.
Virtual DOM
- Method to create virtual DOM:
React.createElement(tagName, properties, children). - Virtual DOM is a JS object that describes the structure of the view.
- Virtual DOM is lightweight compared to the real DOM.
- React converts the virtual DOM into the real DOM for rendering on the page.
React Lifecycle
- New lifecycle methods in React 17:
getDerivedStateFromProps, getSnapshotBeforeUpdate
React CLI
- Command to initialize a React project:
create-react-app projectName. - Default port: 3000
Class Component Render Method
- Role: converts virtual DOM to real DOM and renders it on the page.
State Updates
- Updating state directly is discouraged because
setState triggers React's lifecycle methods.
Props
- Primary role: facilitate value passing and communication between parent and child components.
- Props are modified in the parent component.
Props vs. State
- Props are immutable within the component, while state can be modified.
- State is defined within the component; props are passed from the parent.
Component Types
- Class components are used for complex interactive logic.
- Functional components are used for simple view display.
Functional vs. Class Components
- Class components have state; functional components are stateless.
- Class components have lifecycle methods; functional components do not.
- Functional components are more efficient as they are directly invoked, unlike class components that require instantiation.
this is undefined in functional components; in class components, this refers to the component instance.
Accessing Props
- Functional components:
props.name - Class components:
this.props.name
ShouldComponentUpdate
- Role: controls whether a component should update; used for performance optimization.
- Returns
true to update the component, false to prevent updates. PureComponent uses this lifecycle method for optimization.
Force Update
- API to force a component update:
this.forceUpdate()
Preventing Rendering
- Return
false from shouldComponentUpdate.
- Inherit from
PureComponent. shouldComponentUpdate performs a shallow comparison of state and props.
Optimization Techniques
- Use
shouldComponentUpdate or PureComponent for class components. Use React.memo, useMemo, useCallback for functional components. - Use functional components when state is not needed.
Refs
- Creation methods: string refs (
ref="list"), API (React.createRef()), callback refs (ref={(el) => this.inputRef = el }) - Functional components typically use
React.createRef() as they lack this.
State Lifting
- Moving shared data to a common ancestor component for management.
SetState
- Object-style setState:
setState({}, () => {}) - Functional setState:
setState((state, props) => { return {} }, () => {}) - Functional form receives props and state
CloneElement
- Parameters: element to clone、element properties、element children
- Used to clone React elements or components, configure properties, and/or children.
Component Lifecycle Stages
- Mounting:
constructor, componentWillMount (deprecated), render, componentDidMount - Updating:
componentWillReceiveProps (deprecated), shouldComponentUpdate, componentWillUpdate (deprecated), render, componentDidUpdate - Unmounting:
componentWillUnmount
DOM Manipulation
componentWillMount cannot manipulate the DOM because the component is not yet mounted.
Component Communication
- Parent to child: pass props.
- Child to parent: pass a function as a prop.
- Across levels: Context API.
Context API
- Create context:
React.createContext(). - Components:
Provider, Consumer.
Modifying `this` in Class Components
- Bind method:
onClick={this.add.bind(this)} - Arrow function:
onClick={() => this.add()} - Constructor binding:
this.add = this.add.bind(this); onClick={this.add}
JSX
- Syntactic sugar for
React.createElement used to create virtual DOM. - Requires compilation via React tools for browser execution because it's not natively supported.
JSX Syntax
- Use
className instead of class. - Use
htmlFor instead of for. - Add
key when looping through lists. - Inline styles:
style={{key: value}}. - Only one root tag.
- Tags must be closed.
- No quotes when defining virtual DOM.
- Use
{} to include JS expressions.
JSX Advantages
- More concise and closer to native HTML compared to using
createElement.
React Keys
- Used for efficient virtual DOM updates.
- Avoid using index as key due to potential data order disruption.
Synthetic Events
- React's event object that wraps native DOM events for improved compatibility.
- Uses event delegation to the document.
Event Handling Differences
- React uses synthetic events.
- React delegates events to the document.
- React uses camelCase naming (e.g.,
onClick). - React's events bubble by default; use Capture for the capture phase.
this inside React events is undefined by default; use arrow functions to bind to the component instance.
Deprecated Lifecycle Methods
componentWillMount, componentWillReceiveProps, componentWillUpdate
Mounting Lifecycle Hooks
constructor: creates the instance, initializes state, and binds this.componentWillMount: prepares for initial render (deprecated).render: creates virtual DOM.componentDidMount: post-render tasks like timers, AJAX requests, etc.
Updating Lifecycle Hooks
componentWillReceiveProps: handle incoming props (deprecated).shouldComponentUpdate: determines if the component should re-render.componentWillUpdate: prepares for updates (deprecated).render: updates virtual DOM.componentDidUpdate: post-update tasks.
Unmounting Lifecycle Hook
componentWillUnmount: cleanup tasks like clearing timers and canceling subscriptions.
Lifecycle Triggers
setState: triggers shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate.- Props change: triggers
componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate. forceUpdate: triggers componentWillUpdate, render, componentDidUpdate.
New Lifecycle Hooks
static getDerivedStateFromProps, getSnapshotBeforeUpdate
GetDerivedStateFromProps
this is undefined as it is a static method.- Replaces
componentWillMount and componentWillReceiveProps. - Triggered by parent and current component updates.
GetSnapshotBeforeUpdate
- Used to capture DOM information before updates (e.g., scroll position).
- Parameters:
prevProps, and prevState. - Returns a value passed to
componentDidUpdate. - Exists alongside
componentDidUpdate.
Controlled Components
- Form element values are bound to state.
React Features
- Declarative: uses components.
- Efficient: virtual DOM and DOM diffing.
- Flexible: rich third-party component libraries.
- Uses JSX.
- Easy customization.
- one-way data flow
React vs. Vue
- React: MVC; Vue: MVVM.
- React: manual two-way binding; Vue:
v-model for two-way binding. - React: own algorithm; Vue:
Object.defineProperty (Vue 2.0) or Proxy (Vue 3.0) for data listening. - React:
PureComponent and shouldComponentUpdate; Vue: automatic dependency tracking.
MVVM vs. MVC
- MVVM: Model-View-ViewModel.
- MVC: Model-View-Controller.
- MVVM abstracts presentation logic.
One-Way Data Flow
- Data flows from parent to child components.
- Makes data flow clear.
Rich Text Rendering
- Use
dangerouslySetInnerHTML={{__html:XX}}.
Vue Computed Properties
get m() { return this.state.n } \
set m(val) { this.setState({n: val}) } \
handleClick() { m = 100 } \
render() { return (<div>{m}</div>)}