use-derived-value
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.1 • Public • Published

    use-derived-value

    npm-version codecov

    Implement getDerivedStateFromProps with hook。

    Edit dark-pond-osbps

    Install

    npm install use-derived-value

    Usage

    import React from 'react'
    import useDerivedValue from 'use-derived-value'
    
    const Input = props => {
        const defaultValue = props.defaultValue ?? props.value
        const [state, setState] = useDerivedValue(defaultValue, {
            postState: () => props.value ?? null,
            onChange: props.onChange,
        })
    
        return <input value={state} onChange={setState} />
    }
    
    function App() {
        const [value, setValue] = React.useState('initValue')
        return (
            <Input
                value={value}
                onChange={({ target }) => {
                    setValue(target.value)
                }}
            />
        )
    }

    API

    useDerivedValue<State>(initialState: State, options: Options<State>)
    
    type Options<State> = {
        postState?: () => State | null
        onChange?: (value: State, prevValue: State) => void
    }

    postState is a function, return a new value, if return null mean that is not controlled, it will use state in useDerivedValue.

    onChange will called when set new value, second parameter is the old value.

    Keywords

    none

    Install

    npm i use-derived-value

    DownloadsWeekly Downloads

    3

    Version

    2.0.1

    License

    MIT

    Unpacked Size

    9.51 kB

    Total Files

    9

    Last publish

    Collaborators

    • zhangyu1995