Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Recompose is a React utility belt for function components and higher-order components (HOCs). It provides a set of helper functions to simplify the process of writing and managing HOCs, making it easier to enhance and compose components in a more declarative and functional style.
withState
The `withState` HOC adds state to a functional component. In this example, it adds a `counter` state and a `setCounter` function to the `Counter` component.
const enhance = withState('counter', 'setCounter', 0);
const Counter = enhance(({ counter, setCounter }) => (
<div>
<p>{counter}</p>
<button onClick={() => setCounter(counter + 1)}>Increment</button>
</div>
));
withHandlers
The `withHandlers` HOC allows you to create handler functions that can be passed as props to the component. In this example, it creates an `onClick` handler that increments the `counter` state.
const enhance = withHandlers({
onClick: ({ counter, setCounter }) => () => setCounter(counter + 1)
});
const Counter = enhance(({ counter, onClick }) => (
<div>
<p>{counter}</p>
<button onClick={onClick}>Increment</button>
</div>
));
compose
The `compose` function allows you to combine multiple HOCs into a single HOC. In this example, it combines `withState` and `withHandlers` to create an enhanced `Counter` component.
const enhance = compose(
withState('counter', 'setCounter', 0),
withHandlers({
onClick: ({ counter, setCounter }) => () => setCounter(counter + 1)
})
);
const Counter = enhance(({ counter, onClick }) => (
<div>
<p>{counter}</p>
<button onClick={onClick}>Increment</button>
</div>
));
branch
The `branch` HOC conditionally applies an HOC based on a predicate function. In this example, it renders a loading component if `isLoading` is true, otherwise it renders `MyComponent`.
const enhance = branch(
({ isLoading }) => isLoading,
renderComponent(() => <div>Loading...</div>)
);
const MyComponent = enhance(({ data }) => (
<div>{data}</div>
));
renderNothing
The `renderNothing` HOC renders nothing if the predicate function returns true. In this example, it renders nothing if `shouldRender` is false.
const enhance = branch(
({ shouldRender }) => !shouldRender,
renderNothing
);
const MyComponent = enhance(({ data }) => (
<div>{data}</div>
));
React Hooks provide a way to use state and other React features without writing a class. They offer similar functionality to Recompose but are built into React itself, making them more integrated and easier to use in modern React applications.
Redux is a state management library for JavaScript applications. While it is more complex and powerful than Recompose, it can be used to manage state and side effects in a way that complements React components.
MobX is a state management library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). It offers a different approach to state management compared to Recompose, focusing on observables and reactions.
React-Redux is the official React binding for Redux. It provides a way to connect React components to a Redux store, offering a more structured approach to state management compared to Recompose.
Recompose is a microcomponentization toolkit for React. Think of it like lodash, but for React components.
npm install recompose --save
Documentation is a work-in-progress. Feedback is welcome and encouraged. If you'd like to collaborate on this project, let me know.
Here's an example of a stateful counter component created using only pure functions and Recompose:
import { compose, withState, mapProps } from 'recompose';
const Counter = ({ counter, increment, decrement }) => (
<p>
Count: {counter}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</p>
);
const CounterContainer = compose(
withState('counter', 'setCounter', 0),
mapProps(({ setCounter, ...rest }) => ({
increment: () => setCounter(n => n + 1),
decrement: () => setCounter(n => n - 1),
...rest
}))
)(Counter);
More complex examples are coming soon. Here's a mini React Redux clone from the test suite.
Read on for more about the library, its goals, and how it works.
All functions are available on the top-level export.
import { compose, mapProps, withState /* ... */ } from 'recompose';
The total gzipped size of the entire library is 9.13 kB. You can reduce this number by only including the modules that you need.
All top-level exports can be imported individually:
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import withState from 'recompose/withState';
// ... and so on
This is a good option for library authors who don't want to bloat their bundle sizes.
Recompose includes some lodash modules, like curry
and compose
, as dependencies. If you're already using lodash, then the net bundle increase from using Recompose will be even smaller.
Forget ES6 classes vs. createClass()
. React 0.14 introduces stateless function components, which allow you to express components as pure functions:
const Greeting = props => (
<p>
Hello, {props.name}!
</p>
);
Function components have several key advantages:
setState()
API, favoring props instead.We call the practice of writing small, pure, reusable components microcomponentization.
Note that although Recompose encourages the use of function components whenever possible, it works with normal React components as well.
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.
However, that's only the beginning. 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. Most of these helpers are themselves are higher-order components. You can compose the helpers together to make new HoCs, or apply them to a base component.
If function composition doesn't scare you, then yes, I think so. I believe using higher-order component helpers leads to smaller, more focused components, and provides a better programming model than using classes for operations—like mapProps()
or shouldUpdate()
—that aren't inherently class-y.
That being said, any abstraction over an existing API is going to come with trade-offs. There is a performance overhead when introducing a new component to the tree. I suspect this cost is negligible compared to the gains achieved by blocking subtrees from re-rendering using shouldComponentUpdate()
—which Recompose makes easy with its shouldUpdate()
and onlyUpdateForKeys()
helpers. In the future, I'll work on some benchmarks so we know what we're dealing with.
However, many of Recompose's higher-order component helpers are implemented using stateless function components rather than class components. Eventually, React will include optimizations for stateless components. Until then, we can do our own optimizations by taking advantage of referential transparency. In other words, creating an element from a stateless function is effectively* the same as calling the function and returning its output.
* Stateless function components are not referentially transparent if they access context or use default props; we detect that by checking for the existence of contextTypes
and defaultProps
.
To accomplish this, Recompose uses a special version of createElement()
that returns the output of stateless functions instead of creating a new element. For class components, it uses the built-in React.createElement()
.
I wouldn't recommend this approach for most of the stateless function components in your app. First of all, you lose the ability to use JSX, unless you monkey-patch React.createElement()
, which is a bad idea. Second, you lose lazy evaluation. Consider the difference between these two components, given that Comments
is a stateless function component:
// With lazy evaluation
const Post = ({ title, content, comments, showComments }) => {
const theComments = <Comments comments={comments} />;
return (
<article>
<h1>title</h1>
<div>{content}</div>
{showComments ? theComments : null}
</article>
);
});
// Without lazy evaluation
const Post = ({ title, content, comments, showComments }) => {
const theComments = Comments({ comments });
return (
<article>
<h1>title</h1>
<div>{content}</div>
{showComments ? theComments : null}
</article>
);
});
In the first example, the Comments
function is used to create a React element, and will only be evaluated by React if showComments
is true. In the second example, the Comments
function is evaluated on every render of Post
, regardless of the value of showComments
. This can be fixed by putting the Comments
call inside the ternary statement, but it's easy to neglect this distinction and create performance problems. As a general rule, you should always create an element.
So why does Recompose break this rule? Because it's a utility library, not an application. Just as it's okay for lodash to use for-loops as an implementation detail of its helper functions, it should be okay for Recompose to eschew intermediate React elements as a (temporary) performance optimization.
Recompose functions are component-last and curried by default. This makes them easy to compose:
const BaseComponent = props => {...};
// This will work, but it's tedious
let ContainerComponent = onWillReceiveProps(..., BaseComponent);
ContainerComponent = mapProps(..., ContainerComponent);
ContainerComponent = withState(..., ContainerComponent);
// Do this instead
// Note that the order has reversed — props flow from top to bottom
const ContainerComponent = compose(
withState(...),
mapProps(...),
onWillReceiveProps(...)
)(BaseComponent);
Technically, this also means you can use them as decorators (if that's your thing):
@withState(...)
@mapProps(...)
@onWillReceiveProps(...)
class Component extends React.Component {...}
compose()
is not a higher-order component, as it likely indicates too few parameters were passed to a curried function.FAQs
A React utility belt for function components and higher-order components
The npm package recompose receives a total of 569,425 weekly downloads. As such, recompose popularity was classified as popular.
We found that recompose demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.