npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-multi-state

v1.0.6

Published

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

Downloads

259

Readme

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)
    })()
  }, [setState, setCleanupAfter])

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

↩ Accessing previous state

Currently, there are two ways to access previous state values before update, and they do not require spreading the old state object at all. See the example below.

import { Fragment } from 'react'
function Counter() {
  const [state, setState, { setCount }] = useMultiState({
    count: 0,
    secondCount: 10,
  })

  return (
    <Fragment>
      <button onClick={() => setCount(c => c + 1)}>Update count</button>

      <button
        onClick={() => {
          setState(prevState => ({
            secondCount: prevState.secondCount + 10,
            // use as many `prevState` property values as you wish
          }))
        }}
      >
        Update second count
      </button>
    </Fragment>
  )
}

👀 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)
    })()
  }, [setUsers, setIsFetched])
}

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, useRef } from 'react'

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

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

  return (
    <Fragment>
      <form
        onSubmit={() => {
          setState({
            firstName: firstNameRef.current.value,
            lastName: lastNameRef.current.value,
          })
        }}
      >
        <input type="text" ref={firstNameRef} value={firstName} />
        <input type="text" ref={lastNameRef} value={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, setLesson, ...setters },
  ] = useMultiState({
    title: '',
    lesson: {},
    assignments: null,
    archives: [],
    showModal: false,
  })
  console.log(state, setters)
  //=> { assignments, ... }, { setAssignments: 𝑓, ... }

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

🤝 License

MIT © Olaolu Olawuyi