react-prev-props
Install
npm install --save react-prev-props
About
Little helper to read previous props in getDerivedStateFromProps. Previous props are saved in component local state. Before using this lib, make sure your really want to. Maybe there is better way. Please read:
- react blog - you probably dont need derived state
- react blog - updating state based on props
- react docs - getDerivedStateFromProps
- react blog - 16.4 bugfix for getDerivedStateFromProps
How to use it?
Code example is best description.
Before:
{ const nextState = ; if nextPropsvalue !== thispropsvalue nextStatevalue = nextPropsvalue; if nextPropsvalue2 !== thispropsvalue2 nextStatevalue2 = nextPropsvalue2; if nextPropsvalue3 !== thispropsvalue3 nextStatevalue3 = nextPropsvalue3; this;}
After:
import prevProps from 'react-prev-props'; // ... static { const nextState changedProps = ; if changedProps // props changed, we can insert some additional logic return ...nextState // we can reset state props with changed props ...changedProps return nextState;}
Or:
import resetStateWithChangedProps from 'react-prev-props'; // ... static { return ;}
Or:
import getDerivedStateFromPropsEnhanced from 'react-prev-props'; // ... static { return nextProps prevState;}
How it works?
Prev props are cached in local state. Code example is best explanation.
import prevProps from 'react-prev-props'; // ... static { const nextState changedProps = ; console // => { // _prevProps: { value: 1, value2: 2, value3: 3 }, // value2: 2 // } console // => { value: 1, value2: 999, value3: 3 }; console // => { // _prevProps: { value: 1, value2: 999, value3: 3 }, // value2: 2 // } console // => { value2: 999 } if changedProps // props changed, we can insert some additional logic return ...nextState // we can reset state props with changed props ...changedProps return nextState;}
Or:
import resetStateWithChangedProps from 'react-prev-props'; // ... static { const nextState = ; console // => { // _prevProps: { value: 1, value2: 2, value3: 3 }, // value2: 2 // } console // => { value: 1, value2: 999, value3: 3 }; console // => { // _prevProps: { value: 1, value2: 2, value3: 3 }, // value2: 999 // } return nextState;}
API
@TODO
FAQ
- why nextState can't just look like:instead of:nextState =value: nextPropsvalue?nextState =_prevProps:value: nextPropsvaluevalue: nextPropsvalue
License
MIT © tlareg