Skip to content

Latest commit

 

History

History
68 lines (56 loc) · 4.28 KB

effective-react-receipts.md

File metadata and controls

68 lines (56 loc) · 4.28 KB

Effective React Receipts

Official Website Guide

Stateless functional components are used when a component doesn’t need to maintain its own state or lifecycle methods. Typically, these components have consistent output based on their inputs because they have no state or side effects. If you give a stateless function component a set of props, it will always render the same JSX.

While functional components don’t have direct lifecycle methods, they still go through the same three phases as class components:

  • Mounting: useEffect(() => {}, []): The function inside useEffect runs after the component is first rendered.
  • Updating: useEffect(() => {}): If you omit the dependency array ([]), useEffect will run after every render.
  • Unmounting: useEffect(() => { return () => {} }): The function returned inside useEffect (the cleanup function) is used to clean up resources when the component unmounts or before it re-renders.
// stateless functional component
function _MyPureComponent({ ... }: ComponentProps): {
    return ..
}

// memo the pure function component
const _MyPureComponentWithMemo = React.memo(_MyPureComponent)

// fetch states as props of pure function component
const _MyComponentWithContext = () => {
    const props = { ... } //
    return <_MyPureComponentWithMemo {...props} />
}

// export the component
export const MyComponent = _MyComponentWithContext

Best Practice

  • 组件里的代码都是响应式的 —— 除了顶层的 jsx 逻辑,hook 中都应该是响应式的。需要鉴别清楚什么对于组件来说是响应式代码。
  • 所有 hook 的 deps 依赖都是精确的。存在即需要响应,不应该用 lint ignore 逃逸检查,出现意味着 hook 中有非响应式逻辑,应该提出去。
  • 如果无法摆脱复杂应用中非响应式的组件视图逻辑,或无法清楚区分响应式与非响应式代码,那建议 React 做的事情尽可能少,只把 React 当做渲染器做最纯粹的 JSX 翻译工具。