recompose

0.30.0 · abandoned · verified Tue Apr 21

recompose is a JavaScript utility library for React, providing a collection of higher-order components (HOCs) and utility functions designed to enhance functional component patterns. It allows developers to compose multiple concerns into a single component, such as managing local state (`withState`), handling side effects (`lifecycle`), mapping props (`mapProps`), and creating event handlers (`withHandlers`). The current stable version is 0.30.0, released in late 2018. The author explicitly announced the discontinuation of active maintenance in October 2018, recommending React Hooks as a superior alternative that addresses the same problems and more. Its primary differentiator was enabling a purely functional approach to component logic before the native React Hooks API existed, offering a declarative way to abstract component logic and state management without relying on class components.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a stateful functional React component using `recompose` HOCs like `compose`, `withState`, `withHandlers`, and `lifecycle` for managing count, message, and reacting to mount/update events.

import React from 'react';
import { compose, withState, withHandlers, lifecycle } from 'recompose';

interface CounterProps {
  count: number;
  increment: () => void;
  decrement: () => void;
  message: string;
}

const CounterDisplay: React.FC<CounterProps> = ({ count, increment, decrement, message }) => (
  <div>
    <h1>{message}</h1>
    <p>Count: {count}</p>
    <button onClick={increment}>Increment</button>
    <button onClick={decrement}>Decrement</button>
  </div>
);

const enhance = compose<
  CounterProps,
  { initialCount?: number; initialMessage?: string }
>(
  withState('count', 'setCount', ({ initialCount = 0 }) => initialCount),
  withState('message', 'setMessage', ({ initialMessage = 'Hello Recompose!' }) => initialMessage),
  withHandlers({
    increment: ({ setCount }) => () => setCount((prevCount: number) => prevCount + 1),
    decrement: ({ setCount }) => () => setCount((prevCount: number) => prevCount - 1)
  }),
  lifecycle({
    componentDidMount() {
      console.log('Counter component mounted.');
      this.props.setMessage('Welcome to the Recompose Counter!');
    },
    componentDidUpdate(prevProps: CounterProps) {
      if (this.props.count !== prevProps.count) {
        console.log(`Count changed from ${prevProps.count} to ${this.props.count}`);
      }
    }
  })
);

const EnhancedCounter = enhance(CounterDisplay);

// Example usage in an application (e.g., App.tsx)
// function App() {
//   return (
//     <div style={{ padding: '20px' }}>
//       <EnhancedCounter initialCount={5} />
//     </div>
//   );
// }
// export default App;

view raw JSON →