Use state management style from React class components in function components
setState in class components in React
Playground – play with library in CodeSandbox
First, install the library in your project by npm:
$ npm install react-group-state
Or Yarn:
$ yarn add react-group-state
• Import hook in React application file:
import { useGroupState } from 'react-group-state';
Name | Type | Description |
---|---|---|
state | object | Initial state |
Name | Type | Description |
---|---|---|
state | object | State |
setState | (object or (prevState) => object, (newState) => void) | Function to set new state where the first parameter is new object or function with previous state that returns object and second parameter where value passed to function is updated state |
• Use useGroupState
Hook:
import React from 'react';
import { useGroupState } from 'react-group-state';
const App = () => {
const [state, setState] = useGroupState({
name: 'John',
email: '[email protected]',
age: 21,
});
const updateUserInfo = () => {
setState({
name: 'Paul',
age: 37,
});
};
return (
<>
<p>
{state.name} is {state.age} years old
</p>
<button onClick={updateUserInfo}>Change user name and age</button>
</>
);
};
export default App;
setState(
({ age }) => ({
name: 'Paul',
age: age + 16,
}),
(newState) => console.log(JSON.stringify(newState))
);
This project is licensed under the MIT License © 2020-present Jakub Biesiada