readme.md

✍️ compose-state

compose-state is a library that composes multiple state updaters in React.

compose-state works with the standard setState parameters – objects or functions – so you don’t have to learn any new syntax. It’s also compatible with React’s new getDerivedStateFromProps lifecycle method.

Use

Install

yarn add compose-state or npm install compose-state

Import

API

composeState([updaters])

Returns an updater that can be used with setState. Calling this produces the same result as calling or accessing each given updater from right to left, merging each partial state. If a given updater is a function, its prevState value is the previous state merged with the current partial state.

Arguments

Name

Type

Description

[updaters]

(...Updater)

Functions that can be used with setState, or partial state objects

composeDerivedStateFromProps([updaters])

Returns an updater that can be set as a component's getDerivedStateFromProps static value. Calling this produces the same result as calling or accessing each given updater from right to left, merging each partial state. If a given updater is a function, its prevState value is the previous state merged with the current partial state.

Arguments

Name

Type

Description

[updaters]

(...Updater)

Functions that can be set as a component's getDerivedStateFromProps static value, or partial state objects

Benefits

Simplify your updaters and React code

Let's say you want to call setState and do two things

Increment a score value by 1

Log the current time to an array

Both of these updaters need to be functional, since they rely on the previous state for their return values.

compose-state isn't dependent on React at all, it's just a big reducer function. This allows you to build and compose as many updaters as you want while keeping your actual component code simple and maintainable.

Easily mix functional and object updaters

compose-state accepts both objects and functions, just like setState. This allows you to mix static and dynamic updaters without increasing the complexity of any individual parameter.

While more formal state managers push developers away from controlling state in React, compose-state simply enhances state control methods that are primitive to the platform.

compose-state is a lot like Classnames. It's a helper function that makes setState calls more declarative and easier to construct, just like how Classnames is a helper function that makes className values more declarative and easier to construct.