React Patterns - alexanderteplov/computer-science GitHub Wiki

React Patterns

  1. One-way data flow (passing props down)
  2. Wrapper components
  3. HoC
  4. Render props
  5. Custom hooks
  6. Presentational and Container Components

HoC

A higher-order component is a function that takes a component and returns a new component. The naming convention: withSomething.

Use HOCs For Cross-Cutting Concerns.

Warnings:

  • don't use inside a render() method
  • handle refs manually
  • handle static methods manually

Render props

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>

Use HOCs For Cross-Cutting Concerns.

Warning:

  • be careful when using Render Props with React.PureComponent/React.memo

HoC vs render props vs hooks

HoCs

  • based on composition
  • composable (nesting)
  • testable themself
  • testable components
  • mess the component tree
  • have props collision problem
  • require some boilerplate
  • relatively implicit

Render props

  • based on dependency
  • the less coupled
  • the clearest in usage
  • testable itself
  • testable components
  • no naming collision
  • not composable
  • badly matches with JSX
  • create closure on every render

hooks

  • based on composition
  • composable (nesting)
  • no boilerplate
  • clear component tree
  • not as testable themself
  • hardly testable components

Links

⚠️ **GitHub.com Fallback** ⚠️