managing state in react is now more intelligent.
use-react-state
is an advanced implementation of React's useState
It gives almost the same and more functionality as React's useState.
😢😭😿
import { useState } from 'react'
function Component(){
const [first, setFirst] = useState(1)
const [second, setSecond] = useState(2)
const [third, setThird] = useState(3)
const [fourth, setFourth] = useState(4)
const changeFirstAndSecond = () => {
setFirst(10)
setSecond(20)
// 2x re-render
}
const resetState = () => {
setFirst(1)
setSecond(2)
setThird(3)
setFourth(4)
// 4x re-render
}
}
😊😃😺😄
import useState from 'use-react-state'
function Component(){
const [state, setState] = useState({
first: 1,
second: 2,
third: 3,
fourth: 4,
})
const changeFirstAndSecond = () => {
setState({
first: 10,
second: 20,
})
// 1x re-render
}
const resetState = () => {
setState({
first: 1,
second: 2,
third: 3,
fourth: 4,
})
// 1x re-render
}
}
yarn add use-react-state
import React from 'react'
import useState from 'use-react-state'
const App = () => {
const [state, setState] = useState({ nine: 9 })
return (
<div>
<p>Nine: is {state.nine}</p>
<button onClick={() => setState(({ nine }) => ({ nine: nine + 1 }))}>
Increaae state.nine by 1
</button>
</div>
)
}
is a Hook that lets you add React state to function components.
-
name description type initialState?
state's initial state any
- type
array
-
state
| current state value |any
-
- setState | function to update the state |
function
- setState | function to update the state |
-
stateRef
| state reference |object
import useState from 'use-react-state'
const [state, setState, stateRef] = useState(initialState)
function to update the state. setState is an intelligent setter function which guesses how you intends to update an existing state. When array is passed as the new state, it assumes you will append the newState array with the current state if current state is an array else it replaces the state. same goes for objects.
-
name description type newState|callback
new state to set or setter callback any
Given the 1st example below, setState will merge new state object with existing state given that existing state is an object.
import useState from 'use-react-state'
const [state, setState, stateRef] = useState({ foo: 'foo' })
// merge state object
setState({ bar: 'bar' }) // {foo: 'foo', bar: 'bar'}
// replace state
setState('foo') // 'foo'
// replace state
setState(['foo']) // ['foo']
// push state array
setState(['bar']) // ['foo', 'bar']
// custom state setter
setState((existingDraftState) => {
return ['baz']
}) // ['baz']
using setState's immer produce feature
setState uses immer's produce feature for state mutation. Your are not limited to using the functionality as well.
import useState from 'use-react-state'
const [state, setState] = useState({ foo: 'foo' })
// custom state setter with immer feature
setState((existingDraftState) => {
existingDraftState.bar = 'bar'
}) // {foo: 'foo', bar: 'bar'}
MIT © myckhel