https://github.com/zhangyu1818/use-derived-value
Implement getDerivedStateFromProps with hook。
https://github.com/zhangyu1818/use-derived-value
react react-hooks
Last synced: 9 months ago
JSON representation
Implement getDerivedStateFromProps with hook。
- Host: GitHub
- URL: https://github.com/zhangyu1818/use-derived-value
- Owner: zhangyu1818
- Created: 2021-03-11T14:22:00.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2021-12-24T13:58:16.000Z (almost 4 years ago)
- Last Synced: 2025-01-29T08:44:58.954Z (11 months ago)
- Topics: react, react-hooks
- Language: TypeScript
- Homepage:
- Size: 7.81 KB
- Stars: 2
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-derived-value

[](https://codecov.io/gh/zhangyu1818/use-derived-value)
Implement getDerivedStateFromProps with hook。
[](https://codesandbox.io/s/dark-pond-osbps?fontsize=14&hidenavigation=1&theme=dark)
## Install
```shell
npm install use-derived-value
```
## Usage
```jsx
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
}
function App() {
const [value, setValue] = React.useState('initValue')
return (
{
setValue(target.value)
}}
/>
)
}
```
## API
```typescript
useDerivedValue(initialState: State, options: Options)
type Options = {
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.