Napolean Paced Mischeviously

    react-use-mutable
    TypeScript icon, indicating that this package has built-in type declarations

    0.1.1 • Public • Published

    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)

    Install

    npm i react-use-mutable

    DownloadsWeekly Downloads

    4

    Version

    0.1.1

    License

    Unlicense

    Unpacked Size

    7.23 kB

    Total Files

    13

    Last publish

    Collaborators

    • marik_d