react-group-state

Use state management style from React class components in function components

Usage no npm install needed!

<script type="module">
  import reactGroupState from 'https://cdn.skypack.dev/react-group-state';
</script>

README

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

Name Type Description
state object Initial state

Returned Values

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

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