useSelector
useSelector hook for computing a state from another state
- Usable without external state management libraries
- Composable utility selectors:
selectKey
selectProjection
- Integration with Recoil
- Native Recoil selectors:
keySelector
projection
- Native Recoil selectors:
- Custom selectors (by implementing the
Selector
interface) - Typescript support!
Instal
npm i --save use-selector
Usage
Read only:
const newState = ;
Detailed example:
import React useState from 'react';import useSelectorValue from 'use-selector'; { const title setTitle = ; const text setText = ; const isFormValid = ; return <form> <input = = /> <input = = /> <button = /> </form> ;} ;
Advanced usage
Utility Selectors
;; { const user setUser = ; // Read only select, changes NOT reflected in 'user' const info setInfo = ; // info = { firstName, lastName, photo, title } // Read/Write select (by passing setParent = setInfo) // Changes DO reflect in 'info' const name setName = // name = { firstName, lastName } // ...}
Recoil
;; ; // Read/Write user state in sync with session.user; // RecoilState<User> // Read/Write name state in sync with user;// RecoilState<{ firstName: string, lastName: string }>
Custom Selector
{ return parent + ' mutated' { const internalState = ; // internalState = '${parent} mutated' ; // internalState = `${newValue} set` // parent = newValue, internalState = `${newValue} set` } dependencies: /* dependencies, optional */ ;}