Skip to content

Tiny hook that keeps your react state up-to-date in callbacks.

License

Notifications You must be signed in to change notification settings

dmaretskyi/react-use-mutable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-use-mutable

NPM CircleCI License

Tiny hook that keeps your react state up-to-date in callbacks.

Installation

npm install --save react-use-mutable
yarn add react-use-mutable

Motivation

This library is made for situations where you want to use values from react state in callbacks that get subscribed to events or passed to child components.

Example:

const [count, setCount] = useState(0)

useEffect(() => {
  setInterval(() => {
    console.log(count) // will always print 0 regardless of `count`
  }, 1000) 
}, [])

This happens because count is only captured on initial render and not updated afterwards. To keep the most up-to-date state in callbacks you can wrap them in useMutableCallback hook:

import { useMutableCallback } from 'react-use-mutable'

const [count, setCount] = useState(0)

const printCount = useMutableCallback(() => {
  console.log(count)
})

useEffect(() => {
  setInterval(printCount, 1000) // always prints the latest value
}, [])

Documentation

useMutable

function useMutable<T> (value: T): () => T;

Creates a getter that returns the latest value passed to this hook. All getters, no matter at which point in component lifecycle they were created, return the value from latest render.

useMutableCallback

function useMutableCallback<T extends (...args: any) => any>(callback: T):
  (args: Parameters<T>) => ReturnType<T>

Helper function to apply useMutable to whole callbacks. Returned value can be called directly in the same way as the original.

You don't need to use useMutable inside mutable callbacks.

useMutableState

function useMutableState<S> (initialState?: S): [() => S, (newValue: S) => void]

Works in the same way as React's default useState but returns a getter function as the first value in the tuple.

Can be thought as a combination of useState and useMutable:

const [value, setValue] = useState()
const getValue = useMutable(value)

...

console.log(getValue())

setValue(42)

About

Tiny hook that keeps your react state up-to-date in callbacks.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published