|
| 1 | +# useDerivedState |
| 2 | +Hook useful when the internal state of a component depends on one or more props. It receives an _initial state_ and a _dependency array_ that works the same way as that of a _useEffect_, _useMemo_, and _useCallback_. Every time the dependencies change, the __derived state__ is resetted to _initial state_. A third optional parameter can be passed, to execute a _compute_ function after the dependencies are updated, without having a _useEffect_ within the component. |
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +```tsx |
| 7 | +const WithoutUseDerivedState = memo(({user}:{user:string}) => { |
| 8 | + renders[1]++; |
| 9 | + const [state, setState] = useState<{ loading: boolean, friends: string[] }>({ loading: true, friends: [] }); |
| 10 | + |
| 11 | + useEffect(() => { |
| 12 | + setState({ loading: true, friends: [] }); |
| 13 | + serverAPI(user).then(data => setState({ loading: false, friends: data })); |
| 14 | + }, [user]) |
| 15 | + |
| 16 | + return <> |
| 17 | + <h2>User: {user}</h2> |
| 18 | + <h3>Renders: {renders[1]}</h3> |
| 19 | + { |
| 20 | + state.loading |
| 21 | + ? "Loading..." |
| 22 | + : <ul> |
| 23 | + { |
| 24 | + state.friends.map(f => <li key={f}>{f}</li>) |
| 25 | + } |
| 26 | + </ul> |
| 27 | + } |
| 28 | + </> |
| 29 | +}) |
| 30 | + |
| 31 | +const WithUseDerivedStateAndCompute = memo(({ user }: { user: string }) => { |
| 32 | + renders[2]++; |
| 33 | + const [state, setState] = useDerivedState<{ loading: boolean, friends: string[] }>( |
| 34 | + { loading: true, friends: [] }, |
| 35 | + [user], |
| 36 | + () => { |
| 37 | + state.loading && serverAPI(user).then(data => { |
| 38 | + setState({ loading: false, friends: data }) |
| 39 | + }); |
| 40 | + } |
| 41 | + ); |
| 42 | + |
| 43 | + return <> |
| 44 | + <h2>User: {user}</h2> |
| 45 | + <h3>Renders: {renders[2]}</h3> |
| 46 | + { |
| 47 | + state.loading |
| 48 | + ? "Loading..." |
| 49 | + : <ul> |
| 50 | + { |
| 51 | + state.friends.map(f => <li key={f}>{f}</li>) |
| 52 | + } |
| 53 | + </ul> |
| 54 | + } |
| 55 | + </> |
| 56 | +}) |
| 57 | + |
| 58 | +const WithUseDerivedState = memo(({ user }: { user: string }) => { |
| 59 | + renders[3]++; |
| 60 | + const [state, setState] = useDerivedState<{loading: boolean, friends: string[]}>( |
| 61 | + { loading: true, friends: [] }, |
| 62 | + [user] |
| 63 | + ); |
| 64 | + |
| 65 | + useEffect(() => { |
| 66 | + serverAPI(user).then(data => { |
| 67 | + setState({ loading: false, friends: data }) |
| 68 | + }); |
| 69 | + }, [setState, user]); |
| 70 | + |
| 71 | + return <> |
| 72 | + <h2>User: {user}</h2> |
| 73 | + <h3>Renders: {renders[3]}</h3> |
| 74 | + { |
| 75 | + state.loading |
| 76 | + ? "Loading..." |
| 77 | + : <ul> |
| 78 | + { |
| 79 | + state.friends.map(f => <li key={f}>{f}</li>) |
| 80 | + } |
| 81 | + </ul> |
| 82 | + } |
| 83 | + </> |
| 84 | +}) |
| 85 | + |
| 86 | +export const UseDerivedState = () => { |
| 87 | + const [state, setState] = useState(""); |
| 88 | + const [state1, setState1] = useState(""); |
| 89 | + const [state2, setState2] = useState(""); |
| 90 | + |
| 91 | + return <div style={{ display: "grid", gridTemplateColumns: "auto auto auto", justifyContent: "center", gap: 50 }}> |
| 92 | + <div> |
| 93 | + <p>Without useDerivedState</p> |
| 94 | + <input type="text" placeholder="User.." value={state1} onChange={(e) => setState1(e.target.value)} /> |
| 95 | + <WithoutUseDerivedState user={state1} /> |
| 96 | + </div> |
| 97 | + <div> |
| 98 | + <p>With useDerivedState</p> |
| 99 | + <input type="text" placeholder="User.." value={state} onChange={(e) => setState(e.target.value)} /> |
| 100 | + <WithUseDerivedState user={state}/> |
| 101 | + </div> |
| 102 | + <div> |
| 103 | + <p>With useDerivedState and compute</p> |
| 104 | + <input type="text" placeholder="User.." value={state2} onChange={(e) => setState2(e.target.value)} /> |
| 105 | + <WithUseDerivedStateAndCompute user={state2} /> |
| 106 | + </div> |
| 107 | + </div> |
| 108 | +} |
| 109 | +``` |
| 110 | + |
| 111 | +> The component has _three internal string states_ and renders three input fields and three components that receive one state each. These three components have an object as internal state with two properties _loading_, initially set to __true__, and _friends_ which is an initially empty array. |
| 112 | +> Based on the _user_ prop they receive, they set the _loading_ property of the internal state to __true__ and invoke a _serverAPI_ function that simulates a backend call and returns a list of names filtered by the passed _prop_. This list values the _friends_ property of the internal state and this list together with the passed _user_ prop are rendered: |
| 113 | +> - The _Without useDerivedState_ component uses the _useState_ and _useEffect_ hooks to implement this logic. |
| 114 | +> - The _With useDerivedState_ component uses the _useDerivedState_ hook and the _useEffect_. |
| 115 | +> - The _With useDerivedStateAndCompute_ component uses the _useDerivedState_ hook and the optional third parameter to implement all logic. |
| 116 | +> |
| 117 | +> Each component also renders a counter of the times it is rendered. |
| 118 | +> |
| 119 | +> The component without _useDerivedState_ hook is rendered one more time every time its _prop_ changes while the other two have the same number of renders. |
| 120 | +> |
| 121 | +> Furthermore, if you debug the code you can see how in the first component there is no synchronization in the updating of the values since in a first render the rendered _prop_ user is updated and in a second render the writing `loading` is rendered instead of the list of names. |
| 122 | +
|
| 123 | + |
| 124 | +## API |
| 125 | + |
| 126 | +```tsx |
| 127 | +useDerivedState<T>(initialState: T | (() => T), deps: DependencyList, compute?: EffectCallback): [T, Dispatch<SetStateAction<T>>] |
| 128 | +``` |
| 129 | + |
| 130 | +> ### Params |
| 131 | +> |
| 132 | +> - __initialState__: _T|()=>T_ |
| 133 | +> - __deps__: _DependencyList_ |
| 134 | +dependencies list from which depends derived state. |
| 135 | +> - __compute?__: _EffectCallback_ |
| 136 | +function that will be executed when dependencies list change after resetting derived state to __initialState__. |
| 137 | +> |
| 138 | +
|
| 139 | +> ### Returns |
| 140 | +> |
| 141 | +> __result__: array with a stateful value and a function to update it. |
| 142 | +> - __Array__: |
| 143 | +> - _T_ |
| 144 | +> - _Dispatch<SetStateAction<T>>_ |
| 145 | +> |
0 commit comments