1.0.0-beta.3 • Published 3 years ago

react-group-state v1.0.0-beta.3

Weekly downloads
6
License
MIT
Repository
github
Last release
3 years ago

react-group-state

NPM version NPM downloads NPM license Codecov Travis Bundle size

About

Use state management style from React class components in function components

Idea

setState in class components in React

Alternatives

How to Install

First, install the library in your project by npm:

$ npm install react-group-state

Or Yarn:

$ yarn add react-group-state

Getting Started

• Import hook in React application file:

import { useGroupState } from 'react-group-state';

Params

NameTypeDescription
stateobjectInitial state

Returned Values

NameTypeDescription
stateobjectState
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

Example

• Use useGroupState Hook:

import React from 'react';
import { useGroupState } from 'react-group-state';

const App = () => {
  const [state, setState] = useGroupState({
    name: 'John',
    email: 'john@example.com',
    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))
);

License

This project is licensed under the MIT License © 2020-present Jakub Biesiada