recompose README

The project's README from github.com/acdlite/recompose. As one markdown file: README.md.

A Note from the Author (acdlite, Oct 25 2018):

Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features. Thank you so, so much to @wuct and @istarkov for their heroic work maintaining Recompose over the last few years.

Read more discussion about this decision here.


Recompose

build status coverage code climate npm version npm downloads

Recompose is a React utility belt for function components and higher-order components. Think of it like lodash for React.

Full API documentation - Learn about each helper

Recompose Base Fiddle - Easy way to dive in

npm install recompose --save

📺 Watch Andrew's talk on Recompose at React Europe. (Note: Performance optimizations he speaks about have been removed, more info here)

recompose-relay — Recompose helpers for Relay

You can use Recompose to...

...lift state into functional wrappers

Helpers like withState() and withReducer() provide a nicer way to express state updates:

const enhance = withState('counter', 'setCounter', 0)
const Counter = enhance(({ counter, setCounter }) =>
  <div>
    Count: {counter}
    <button onClick={() => setCounter(n => n + 1)}>Increment</button>
    <button onClick={() => setCounter(n => n - 1)}>Decrement</button>
  </div>
)

Or with a Redux-style reducer:

const counterReducer = (count, action) => {
  switch (action.type) {
  case INCREMENT:
    return count + 1
  case DECREMENT:
    return count - 1
  default:
    return count
  }
}

const enhance = withReducer('counter', 'dispatch', counterReducer, 0)
const Counter = enhance(({ counter, dispatch }) =>
  <div>
    Count: {counter}
    <button onClick={() => dispatch({ type: INCREMENT })}>Increment</button>
    <button onClick={() => dispatch({ type: DECREMENT })}>Decrement</button>
  </div>
)

...perform the most common React patterns

Helpers like componentFromProp() and withContext() encapsulate common React patterns into a simple functional interface:

const enhance = defaultProps({ component: 'button' })
const Button = enhance(componentFromProp('component'))

<Button /> // renders <button>
<Button component={Link} /> // renders <Link />
const provide = store => withContext(
  { store: PropTypes.object },
  () => ({ store })
)

// Apply to base component
// Descendants of App have access to context.store
const AppWithContext = provide(store)(App)

...optimize rendering performance

No need to write a new class just to implement shouldComponentUpdate(). Recompose helpers like pure() and onlyUpdateForKeys() do this for you:

// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}

// Optimized version of same component, using shallow comparison of props
// Same effect as extending React.PureComponent
const OptimizedComponent = pure(ExpensiveComponent)

// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)

...interoperate with other libraries

Recompose helpers integrate really nicely with external libraries like Relay, Redux, and RxJS

const enhance = compose(
  // This is a Recompose-friendly version of Relay.createContainer(), provided by recompose-relay
  createContainer({
    fragments: {
      post: () => Relay.QL`
        fragment on Post {
          title,
          content
        }
      `
    }
  }),
  flattenProp('post')
)

const Post = enhance(({ title, content }) =>
  <article>
    <h1>{title}</h1>
    <div>{content}</div>
  </article>
)

...build your own libraries

Many React libraries end up implementing the same utilities over and over again, like shallowEqual() and getDisplayName(). Recompose provides these utilities for you.

// Any Recompose module can be imported individually
import getDisplayName from 'recompose/getDisplayName'
ConnectedComponent.displayName = `connect(${getDisplayName(BaseComponent)})`

// Or, even better:
import wrapDisplayName from 'recompose/wrapDisplayName'
ConnectedComponent.displayName = wrapDisplayName(BaseComponent, 'connect')

import toClass from 'recompose/toClass'
// Converts a function component to a class component, e.g. so it can be given
// a ref. Returns class components as is.
const ClassComponent = toClass(FunctionComponent)

...and more

API docs

Read them here

Flow support

Read the docs

Translation

Traditional Chinese

Why

Forget ES6 classes vs. createClass().

An idiomatic React application consists mostly of function components.

const Greeting = props =>
  <p>
    Hello, {props.name}!
  </p>

Function components have several key advantages:

(Note that although Recompose encourages the use of function components whenever possible, it works with normal React components as well.)

Higher-order components made easy

Most of the time when we talk about composition in React, we're talking about composition of components. For example, a <Blog> component may be composed of many <Post> components, which are composed of many <Comment> components.

Recompose focuses on another unit of composition: higher-order components (HoCs). HoCs are functions that accept a base component and return a new component with additional functionality. They can be used to abstract common tasks into reusable pieces.

Recompose provides a toolkit of helper functions for creating higher-order components.

Should I use this? Performance and other concerns

Usage

All functions are available on the top-level export.

import { compose, mapProps, withState /* ... */ } from 'recompose'

Note: react is a peer dependency of Recompose. If you're using preact, add this to your webpack.config.js:

resolve: {
  alias: {
    react: "preact"
  }
}

Composition

Recompose helpers are designed to be composable:

const BaseComponent = props => {...}

// This will work, but it's tedious
let EnhancedComponent = pure(BaseComponent)
EnhancedComponent = mapProps(/*...args*/)(EnhancedComponent)
EnhancedComponent = withState(/*...args*/)(EnhancedComponent)

// Do this instead
// Note that the order has reversed — props flow from top to bottom
const enhance = compose(
  withState(/*...args*/),
  mapProps(/*...args*/),
  pure
)
const EnhancedComponent = enhance(BaseComponent)

Technically, this also means you can use them as decorators (if that's your thing):

@withState(/*...args*/)
@mapProps(/*...args*/)
@pure
class Component extends React.Component {...}

Optimizing bundle size

Since 0.23.1 version recompose got support of ES2015 modules. To reduce size all you need is to use bundler with tree shaking support like webpack 2 or Rollup.

Using babel-plugin-lodash

babel-plugin-lodash is not only limited to lodash. It can be used with recompose as well.

This can be done by updating lodash config in .babelrc.

 {
-  "plugins": ["lodash"]
+  "plugins": [
+    ["lodash", { "id": ["lodash", "recompose"] }]
+  ]
 }

After that, you can do imports like below without actually including the entire library content.

import { compose, mapProps, withState } from 'recompose'

Debugging

It might be hard to trace how does props change between HOCs. A useful tip is you can create a debug HOC to print out the props it gets without modifying the base component. For example:

make

const debug = withProps(console.log)

then use it between HOCs

const enhance = compose(
  withState(/*...args*/),
  debug, // print out the props here
  mapProps(/*...args*/),
  pure
)

Who uses Recompose

If your company or project uses Recompose, feel free to add it to the official list of users by editing the wiki page.

Recipes for Inspiration

We have a community-driven Recipes page. It's a place to share and see recompose patterns for inspiration. Please add to it! Recipes.

Feedback wanted

Project is still in the early stages. Please file an issue or submit a PR if you have suggestions! Or ping me (Andrew Clark) on Twitter.

Getting Help

For support or usage questions like “how do I do X with Recompose” and “my code doesn't work”, please search and ask on StackOverflow with a Recompose tag first.

We ask you to do this because StackOverflow has a much better job at keeping popular questions visible. Unfortunately good answers get lost and outdated on GitHub.

Some questions take a long time to get an answer. If your question gets closed or you don't get a reply on StackOverflow for longer than a few days, we encourage you to post an issue linking to your question. We will close your issue but this will give people watching the repo an opportunity to see your question and reply to it on StackOverflow if they know the answer.

Please be considerate when doing this as this is not the primary purpose of the issue tracker.

Help Us Help You

On both websites, it is a good idea to structure your code and question in a way that is easy to read to entice people to answer it. For example, we encourage you to use syntax highlighting, indentation, and split text in paragraphs.

Please keep in mind that people spend their free time trying to help you. You can make it easier for them if you provide versions of the relevant libraries and a runnable small project reproducing your issue. You can put your code on JSBin or, for bigger projects, on GitHub. Make sure all the necessary dependencies are declared in package.json so anyone can run npm install && npm start and reproduce your issue.

recompose (acdlite/recompose)

Searching Database…

14.8K ·GitHub
archived
这是干什么的?Recompose 是一个针对函数组件和高阶组件的 React 工具集——可以把它理解为 React 界的 lodash:它是一整套小巧、可组合的辅助函数工具包,而不是一个应用或框架。
它是装进现有 React 应用里的库,还是更大的东西?它就是一个普通的 npm 辅助函数库,你用它来包装自己的组件;React 本身是由你自己提供的 peer dependency。它围绕函数组件和高阶组件(HoC)构建,不过对普通的 class 组件也能用。
怎么把它装进项目里?从 npm 安装(npm install recompose),然后从顶层导出里引入任意一个辅助函数。如果不想做任何配置就想先看看效果,浏览器里直接打开 Recompose Base Fiddle 就行。
它只能配合 React 用,还是 Preact 也行?它面向 React,但也能跑在 Preact 上——只要在 webpack.config.js 里加上常规的 alias 配置即可。它还自带 Flow 类型支持。
Recompose 还在活跃维护吗?不了。作者加入了 React 团队,并在 2018 年 10 月宣布停止活跃维护,推荐改用 Hooks,因为 Hooks 解决的是同样的问题。已有代码仍然可以正常工作,但别指望有新功能了。
这些辅助函数到底能做什么?它们通过 withState() 和 withReducer()(Redux 风格的 reducer)把状态提升到函数式包装里,封装 componentFromProp() 和 withContext() 这类常见 React 模式,用 pure() 和 onlyUpdateForKeys() 优化渲染,还提供 shallowEqual() 和 getDisplayName() 这类通用工具函数——否则各个 React 库都得反复自己实现一遍。
不用 class 组件,它是怎么优化渲染的?pure() 和 onlyUpdateForKeys() 这类辅助函数帮你实现了 shouldComponentUpdate(),所以不用写 class 也能获得基于类的渲染拦截。所有辅助函数都设计成可组合的,通常用 compose() 串起来一起用。
它能配合 Redux、RxJS 或 Relay 使用吗?可以——README 里特别强调 Recompose 的辅助函数能与 Relay、Redux、RxJS 这类外部库很好地集成,并把该项目定位为构建你自己的基于 HoC 的库时的共享工具箱。
我能让打包体积保持很小吗?从 0.23.1 版本起,Recompose 以 ES2015 模块形式发布,所以配合支持 tree shaking 的打包工具(如 webpack 2 或 Rollup),只会打包你实际引入的部分。babel-plugin-lodash 也可以配置成支持 recompose 的导入。
What are similar projects?jotai, zustand, cyclejs, redux-form, Recoil, hooks, date-fns, normalizr
Creator
acdlite
Size
1.3 MB
Stars
14.8K
Age
11y
Commits · 90 Days