react-use-setstate

1.0.2 • Public • Published

React useSetState | RUSS

Batched updates for React function components, replicating the [good old] class components "setState"'s behavior.

NPM JavaScript Style Guide

History

This library came to the world as a StackOverflow answer that I made a while back. The question is "How to prevent multiple re-renders when you do multiple calls to state updater from useState".

There's also a discussion around this matter in React Github issues.

Due to the interest that people showed in the answer, I decided to make it into this library.

Install

npm install --save react-use-setstate

or [better]

yarn add react-use-setstate

Usage

import React from 'react'
import useSetState from 'react-use-setstate'

const SomeComponent = () => {
  const [state, setState] = useSetState({
    data: [],
    loading: true,
  })

  const fetchData = () => {
    setState(prevState => ({
      data: [1, 2, 3],
      loading: false
    }))
  }
}

Example

import React from 'react'
import useSetState from 'react-use-setstate'

const SomeComponent = () => {
  const [state, setState] = useSetState({
    searchQuery: '',
    data: [],
    loading: true,
  })

  React.useEffect(() => {
    setState({loading: true})
    fetch(`https://jsonplaceholder.typicode.com/users/1/todos?q=${state.searchQuery}`)
      .then(response => response.json())
      .then(json => {
        setState({data: json, loading: false})
      })
  }, [state.searchQuery])

  return (
    <div>
      <input 
        onChange={(e) => {
          setState({searchQuery: e.target.value})
        }}
        value={state.searchQuery}
        placeholder={'Type to search...'}
      />
      <ul>
        {state.loading ? 'Loading...': state.data.map(d => (
          <li key={d.id}>{d.title}</li>
        ))}
      </ul>
    </div>
  )
}

Example With Previous State

import React from 'react'
import useSetState from 'react-use-setstate'

const SomeComponent = () => {
  const [state, setState] = useSetState({
    counter: 0,
  })

  React.useEffect(() => {
    const interval = setInterval(() => {
      setState(prevState => ({counter: prevState.counter + 1}))
    }, 1000)

    return () => clearInterval(interval)
  }, [])

  return (
    <div>
      <p>Counter</p>
      <p>{state.counter}</p>
    </div>
  )
}

License

MIT © thevahidal


This hook is created using create-react-hook.

Readme

Keywords

none

Package Sidebar

Install

npm i react-use-setstate

Weekly Downloads

37

Version

1.0.2

License

MIT

Unpacked Size

120 kB

Total Files

25

Last publish

Collaborators

  • thevahidal