Lagily / react-multi-state

🦍Declarative, simplified way to handle complex local state with hooks.

Home Page:https://npm.im/react-multi-state

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react-multi-state

🦍Declarative, simplified way to handle complex local state with hooks.

✨ Features

  • 📦 ~286b (gzipped)
  • 🔥 Easy to scale
  • 🙅‍♂️ Zero dependencies
  • ✂️ Super-flexible API
  • ✅ Fully tested and reliable
  • 🌈 More declarative than React.useState
  • ⚒ CommonJS, ESM & browser standalone support

🔧 Installation

You can easily install this package with yarn or npm:

$ yarn add react-multi-state

or

$ npm install --save react-multi-state

📖 Usage

The function takes in an object of initial state and returns an array containing three elements – state, setState and setters:

  • state, which contains the current state of the component.
  • setState, which is a multi-action dispatcher that takes in a new state object.
  • setters, which contains composed dispatchAction functions for each state property.

Here is a simple example:

import React, { useEffect } from 'react'
import useMultiState from 'react-multi-state'

export default function Users() {
  const [state, setState, { setCleanupAfter }] = useMultiState({
    users: [],
    isFetched: false,
    cleanupAfter: false,
  })

  useEffect(() => {
    ;(async function() {
      const usersData = await getUsers()
      setState({ isFetched: true, users: usersData })
      setCleanupAfter(true)
    })()
  }, [])

  return (
    <ul>
      {state.users.map(({ name }) => (
        <li class="user">{name}</li>
      ))}
    </ul>
  )
}

👀 Comparison with React.useState (examples)

With React.useState, you'd have to call useState and the individual dispatcher functions multiple times which is hard to scale and can get messy real quick as the complexity of your component increases. For example:

import React, { useState, useEffect } from 'react'

export default function Users() {
  const [users, setUsers] = useState([])
  const [userName, setUserName] = useState('')
  const [gender, setGender] = useState('M')
  const [isFetched, setIsFetched] = useState(false)

  useEffect(() => {
    ;(async function() {
      const usersData = await getUsers()
      setUsers(usersData)
      setIsFetched(true)
    })()
  }, [])
}

Meanwhile, with useMultiState, all you need is a state object, and you can update as many properties as you want at once like:

import { Fragment } from 'react'

function Form() {
  const [{ firstName, lastName }, setState, setters] = useMultiState({
    firstName: '',
    lastName: '',
  })

  console.log(setState, setters)
  //=> { setState: 𝑓 }, { setFirstName: 𝑓, setLastName: 𝑓 }

  return (
    <Fragment>
      <form
        onSubmit={event => {
          const { elements } = event.target
          setState({
            firstName: elements.firstName,
            lastName: elements.lastName,
          })
        }}
      >
        <input type="text" name="firstName" />
        <input type="text" name="lastName" />
        <button type="submit">Submit</button>
      </form>

      <h2>
        My full name is {firstName} {lastName}
      </h2>
    </Fragment>
  )
}

💡 More examples

If you prefer dedicated dispatcher functions instead, useMultiState supports that too. Each time you add a property to the state object, a new setter based on the property name is composed and attached to the setters object. So if you like to destructure, you can easily create variables for your state and setters without worrying about defining them in any particular order, contrary to React.useState. For instance:

function Title() {
  const [{ title, lesson }, , { setTitle, setLesson }] = useMultiState({
    title: 'Unicorns',
    lesson: {},
    assignments: null,
    archives: [],
    showModal: false,
  })

  const updateTitle = title => setTitle('Title: ' + title)
  console.log(title, setLesson)
  //=> "Unicorns", 𝑓 setLesson()

  return <h1>{title}</h1>
}

Notice how the second element (setState) is omitted in the above example.

Better still, you can consume the properties directly from the state and setters object, like so:

function Title() {
  const [state, , setters] = useMultiState({
    title: '',
    lesson: {},
    assignments: null,
    archives: [],
    showModal: false,
  })

  const updateTitle = title => setters.setTitle('Title: ' + title)
  console.log(state, setters)
  //=> { title, ... }, { setTitle: 𝑓, ... }

  return <h1>{state.title}</h1>
}

Or... destructure some properties and accumulate the rest into state and setters objects:

function Title() {
  const [
    { title, lesson, ...state },
    setState,
    { setTitle, ...setters },
  ] = useMultiState({
    title: '',
    lesson: {},
    assignments: null,
    archives: [],
    showModal: false,
  })
  console.log(state, setters)
  //=> { assignments, ... }, { setAssignments: 𝑓, ... }

  return <h1>{title}</h1>
}

Using Arrays

To make working with arrays in an immutable fashion inside the state easier, the following helper functions are available in the setters object:

  • add
  • remove
  • replace

These helpers are added, if the property in your state is an array. If your property ends in an 's', it is ommited for these helpers. So if you have a property called items, your helper functions will be addHelper(newItem), removeHelper(index) and replaceHelper(index, newItem)

  function TodoList() {
    const [state, setState, setters] = useMultiState({
      todos: [],
    })
    const { todos } = state
    const { setTodos, addTodo, replaceTodo, removeTodo } = setters

    return (
      <div>
        <h1>Todo List</h1>
        <div>
          <ul class="todos-list">
            {todos.map((t, idx) => (
              <li key={idx}>{t}</li>
            ))}
          </ul>
          <button
            class="btn-add-todos"
            onClick={() => addTodo('Simple-Todo')}
          >
            Update Todo
          </button>
          <button class="btn-reset-todos" onClick={() => setTodos([])}>
            Reset Todos
          </button>
          <button
            class="btn-replace-first-todo"
            onClick={() => replaceTodo(0, 'Replaced-Todo')}
          >
            Update First Todo
          </button>
          <button
            class="btn-remove-first-todo"
            onClick={() => removeTodo(0)}
          >
            Remove First Todo
          </button>
        </div>
      </div>
    )
  }

🤝 License

MIT © Olaolu Olawuyi

About

🦍Declarative, simplified way to handle complex local state with hooks.

https://npm.im/react-multi-state

License:MIT License


Languages

Language:JavaScript 100.0%