A custom hook that makes it easy when working with complex state in react

react-complex-state

A custom hook that makes it easy when working with complex state in react.

When to use it?

Consider using it when you have a complex state, such as an array of strings or array of objects. Essentially, the state must contain an array of any data type.

Installation

Npm :

$ npm install react-complex-state

Yarn :

$ yarn add react-complex-state

Pnpm :

$ pnpm add react-complex-state

Usage

Pass the state you want to use in useComplexState hook like you do in useState.

import { useComplexState } from "react-complex-state";

function App() {
  const complexState = useComplexState(["John", "William"]);

  return (
    <>
      <div>
        {complexState.value.map((item) => (
          <p key={item}>{item}</p>
        ))}
      </div>
      <button onClick={() => complexState.insert("Noah")}>Add</button>
    </>
  );
}

export default App;

Returns

return type description
value array The data of your state.
setValue function The usual setState function. Use it if you want control over your state.
insert function (data: T, index?: number) => void Add data to your state at an index. By default it will add the data at the end.
insertMany function (data: T[], index?: number) => void Add array of data to your state at an index. Defaults are similar to insert function.
update function (data: T, index: number) => void Update your state data at an index.
partialUpdate function (data: Partial<T>, index: number) => void Update only the data that you passed at an index. Other remaining data will be unchanged. (Only usable when your state contains array of objects)
partialUpdateMany function (data: Partial<T>, indexes: number[]) => void Similar to partialUpdate function but update multiple data at once.
remove function (index: number) => void Delete your state data at an index.
removeMany function (indexes: number[]) => void Delete multiple data of your state at provided indexes.

License

MIT

GitHub

View Github