Component autonomous state control utilities in React class methods and React Hooks
npm install react-auto-controlled- Why?
- Installation
- Usage
- Hook Function
- State Manager Class (modern)
- State Manager Class (legacy)
- Contribution
- License
(semantic-ui-react) is not exported. (@stardust-ui/react) requires dependencies to other modules that you don't need.class components.Enter this library. Its utilities behave roughly in the manner you'd expect if you were to use , with some differences. Include support for a Hook-based counterpart and you get react-auto-controlled.
You'll need React preinstalled in order to use this library.
NPM
``sh`
npm install --save react
npm install --save react-auto-controlled
Yarn
`sh`
yarn add react
yarn add react-auto-controlled
This package contains definitions for TypeScript.
You don't need to install a @types/react-auto-controlled module.
All examples are written in TypeScript. Pure JavaScript developers are encouraged to read along.
The examples below assume a component called will be used this way:
`jsx
import { Counter } from './Counter';
export function App() {
// Details:
// 1. Without a prop, the counter component starts at 0, incrementing itself when its button is clicked.defaultProp
// 2. With a , the counter component starts at 20, incrementing itself when its button is clicked.value
// 3. With a , the counter component will not update its value unless the user provides a value prop.`
return (
);
}
Demo: https://github.com/andrewsantarin/react-16-auto-controlled-hook/tree/master/
Unlike a State Manager Class, a Hook only manages one slice of the state, similar to the React useState hook.useState
By using Hooks, you gain more control over which state you'd prefer to update. However, in the spirit of ,
you have to invoke the state modifer one by one if you want to update multiple states at once.
`tsx
import React, { useCallback } from 'react';
import { useAutoControlled } from 'react-auto-controlled';
interface CounterProps {
otherProp?: string;
value?: number;
defaultValue?: number;
name?: string;
defaultName?: string;
}
export function Counter(props) {
const [
value, // original React.useState pattern
setValue, // original React.useState pattern
trySetValue,
getDerivedValueFromProp
] = useAutoControlled(0, {
prop: props.value, // optional
defaultProp: props.defaultValue, // optional
});
const [
name, // original React.useState pattern
setName, // original React.useState pattern
trySetName,
getDerivedNameFromProp
] = useAutoControlled('Andrew', {
prop: props.name, // optional
defaultProp: props.defaultName, // optional
});
getDerivedValueFromProp(); // Similar to getDerivedStateFromProps, except no argument and state slice only.
getDerivedNameFromProp(); // Similar to getDerivedStateFromProps, except no argument and state slice only.
const handleClick = useCallback(() => {
trySetValue(value + 1);
trySetName('Bob');
}, [ trySetValue, value ]);
return (
$3
For React v16.3+Demo: https://github.com/andrewsantarin/react-16-auto-controlled-class/tree/master/
The Class State Manager offers a set of methods in order to autocontrol state. Unlike
,
it's not an extension of the React Component class. You'll need to declare your own class component separately.This approach was taken in order to reduce
static attribute pollution on the component class, which can also
be potentially overridden by an unattentive developer. The manager's methods are immutable (Object.freeze(this)).>If you use earlier versions of React which aren't shipped with the
>
static getDerivedStateFromProps(nextProps, prevState)
>component function, refer to the legacy example instead.`tsx
import React, { Component } from 'react';
import { AutoControlledManager, AutoControlled } from 'react-auto-controlled';interface CounterProps = {
otherProp?: string;
value?: number;
defaultValue?: number;
name?: string;
defaultName?: string;
};
type CounterState = Required<
Pick
>;
const counterAutoControlledManager = new AutoControlledManager(
[
// A list of class component props you want to auto-control
'value',
'name',
],
{
// State initializer
getInitialAutoControlledState() {
return {
active: false,
name: 'Andrew',
level: 0,
};
}
}
);
export class Counter
extends Component
implements AutoControlled // Enforce the
.trySetState(maybeState, callback?) class method.
{
// Use constructor if you have custom logic in the state / attribute / method assignment.
constructor(props: CounterProps) {
super(props); this.state = counterAutoControlledManager.getInitialAutoControlledStateFromProps(props);
}
// Take this approach if you have zero custom logic. Just use
this.props. Convenient!
state = counterAutoControlledManager.getInitialAutoControlledStateFromProps(this.props); // Apply the manager functions to the corresponding component methods.
static getDerivedStateFromProps = counterAutoControlledManager.getDerivedStateFromProps;
trySetState = counterAutoControlledManager.trySetState;
handleClick = () => {
// Replace
this.setState() with this.trySetState() to achieve auto-control.
this.trySetState({
value: this.state.value + 1,
name: 'Bob',
});
} render() {
const { value, name } = this.state;
return (
Hello, {name}!
);
}
}
`$3
For React 15.0 ~ React 16.2>⚠️ This library has been tested with React v16.8.x. ⚠️
>
>The maintainer(s) can't guarantee that this approach will always work.
>
>Consider upgrading your project's React dependency to at least v16.3.
Demo: https://codesandbox.io/s/github/andrewsantarin/react-15-auto-controlled-class/tree/master/
The Class State Manager offers a set of methods in order to autocontrol state.
static getDerivedStateFromProps(nextProps, prevState) component function, which this library intends to enhance, is unavailable to you in earlier version of React. You can subsitute it with a combination of:
- componentWillReceiveProps(nextProps) lifecycle function
- this.state in the lifecycle implementation.`tsx
import React, { Component } from 'react';
import { AutoControlledManager, AutoControlled } from 'react-auto-controlled';interface CounterProps = {
otherProp?: string;
value?: number;
defaultValue?: number;
name?: string;
defaultName?: string;
};
type CounterState = Required<
Pick
>;
const counterAutoControlledManager = new AutoControlledManager(
[
// A list of class component props you want to auto-control
'value',
'name',
],
{
// State initializer
getInitialAutoControlledState() {
return {
active: false,
name: 'Andrew',
level: 0,
};
}
}
);
export class Counter
extends Component
implements AutoControlled // Enforce the
.trySetState(maybeState, callback?) class method.
{
// Use constructor if you have custom logic in the state / attribute / method assignment.
constructor(props: CounterProps) {
super(props); this.state = counterAutoControlledManager.getInitialAutoControlledStateFromProps(props);
}
// Take this approach if you have zero custom logic. Just use
this.props. Convenient!
state = counterAutoControlledManager.getInitialAutoControlledStateFromProps(this.props); componentWillReceiveProps(nextProps: CounterProps) {
const newState = counterAutoControlledManager.getDerivedStateFromProps(
nextProps,
this.state // This should behave roughly like the
prevState callback parameter.
); if (newState === null) {
return;
}
// Apply the state changes.
this.setState(newState);
}
// Apply the manager functions to the corresponding component methods.
trySetState = counterAutoControlledManager.trySetState;
handleClick = () => {
// Replace
this.setState() with this.trySetState() to achieve auto-control.
this.trySetState({
value: this.state.value + 1,
name: 'Bob',
});
} render() {
const { value, name } = this.state;
return (
Hello, {name}!
);
}
}
`Contribution
This library is still very much a work in progress was hastily started so that it can be used immediately in bigger projects.Ideas & support are more than welcome!
1. Fork the project.
2. Run the project in development mode:
yarn develop.
3. Make changes to the code.
4. Add new tests.
5. Test the code: yarn test. If the tests fail, check the code again. Make sure the tests pass!
6. Lint the code: yarn lint`. Clean up all linting errors._See: LICENSE.md_
MIT.