Comments (10)
First your useStateActions hook is not concurrent mode safe, as the value of state during render is not guaranteed to be the most recent state value (React batches state updates). Also note that the setState function returned by useState is more aptly named updateState. Hence in your second example you could write:
export default function Counter() {
const [state, updateState] = useState({ count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => updateState(({ count}) => ({ count: count - 3})}>-</button>
<button onClick={() => updateState(({ count}) => ({ count: count + 5})}>+</button>
</>
);
}
from rfcs.
You can't reliably capture the most recent state in a ref for the purpose of updating state from a previous state, because react doesn't render all of your states. First instance, it's possible to dispatch multiple updateState calls that are applied sequentially in a batch, but without rendering the intermediate results. The best solution I have to what your proposing is to memoize your callbacks. Internally I have such a hook.
function useStateWithUpdaters<TState, TUpdaters>(
defaultState: TState,
createStateUpdaters: (
updateState: (f: (TState) => TState) => void,
) => TUpdaters,
): [TState, TUpdaters] {
const [state, updateState] = useState(defaultState);
const updaters = useMemo(() => createStateUpdaters(updateState), [
createStateUpdaters,
updateState,
]);
return [state, updaters];
}
const createStateupdaters = updateState => {
const add = n => updateState(prev =>({ ...prev, count: prev.count + n }));
const subtract = n => updateState(prev =>({ ...prev, count: prev.count - n }));
return { add, subtract };
}
const MyComponent = () => {
const [{ count }, { add, subtract } = useStateWithUpdaters({ count: 0}, createStateupdaters);
return <div>{ count }</div>;
}
from rfcs.
A little bit improved TypeScript version (keep updater parameters typing)
import { Dispatch, SetStateAction, useMemo, useState } from 'react';
type Tail<TState extends Object, T extends any[]> = T extends [TState, ...infer X] ? X : [];
type Updaters<TState extends Object> = Record<string, (prevState: TState, ...params: any[]) => TState>;
type WrappedUpdaters<TState extends Object, TUpdaters extends Updaters<TState>> = {
[m in keyof TUpdaters]: (...args: Tail<TState, Parameters<TUpdaters[m]>>) => TState;
};
// Creates wrapper functions for original updaters and pass current state and arguments to original updaters
function wrapUpdaters<TState extends Object, TUpdaters extends Updaters<TState>>(
rawUpdaters: TUpdaters,
updateState: Dispatch<SetStateAction<TState>>,
) {
return Object.entries(rawUpdaters).reduce((acc: any, [method, updater]) => {
acc[method] = (...params: any[]) => {
updateState(prevState => updater(prevState, ...params));
};
return acc;
}, {} as WrappedUpdaters<TState, TUpdaters>);
}
/**
* @see https://github.com/reactjs/rfcs/issues/185#issuecomment-764866437
* @example
* interface CounterState {
* count: number;
* }
*
* const updaters = {
* subtract: (prevState: CounterState, value: number) => ({
* ...prevState,
* count: prevState.count - value
* }),
* add: (prevState: CounterState, value: number) => ({
* ...prevState,
* count: prevState.count + value
* })
* };
*
* const MyComponent = () => {
* const [{ count }, { subtract, add }] = useStateWithUpdaters(
* { count: 0 },
* updaters
* );
* return (
* <div>
* Count: {count}
* <button onClick={() => subtract(1)}>-</button>
* <button onClick={() => add(1)}>+</button>
* </div>
* );
* };
*/
export function useStateWithUpdaters<TState extends Object, TUpdaters extends Updaters<TState>>(
defaultState: TState,
rawUpdaters: TUpdaters,
): [TState, WrappedUpdaters<TState, TUpdaters>] {
const [state, updateState] = useState(defaultState);
const updaters = useMemo(() => wrapUpdaters(rawUpdaters, updateState), [rawUpdaters]);
return [state, updaters];
}
from rfcs.
@bordoley, thanks!
I don't have experience with concurrent mode.
How to fix my hook?
It is will work in concurrent mode if the currentStateRef.current = state;
line will moved into useEffect like below?
function useStateActions(actions, initialState) {
const [state, setState] = useState(initialState);
const actionsRef = useRef({});
const currentStateRef = useRef(state);
// currentStateRef.current = state; // old code
useEffect(() => {
// Creating wrapper functions for original actions and pass current state and arguments to original actions
for (let actionName in actions) {
actionsRef.current[actionName] = (...params) => {
// new 3 lines:
const newState = actions[ actionName ](currentStateRef.current, ...params);
setState(newState);
currentStateRef.current = newState;
};
}
}, []); // for call only on mount
return [state, actionsRef.current];
}
Hence in your second example you could write: ...
I know, but my second example was written for demonstration an easier useReducer alternative.
useReducer example:
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + action.value};
case 'decrement':
return {count: state.count - action.value};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement', value: 3})}>-</button>
<button onClick={() => dispatch({type: 'increment', value: 5})}>+</button>
</>
);
}
Alternative example:
const actions = {
subtract: (state, value) => ({ count: state.count - value }),
add: (state, value) => ({ count: state.count + value })
};
function Counter() {
const [state, stateActions] = useStateActions(actions, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => stateActions.subtract(3)}>-</button>
<button onClick={() => stateActions.add(5)}>+</button>
</>
);
}
from rfcs.
Thanks!
But I would to get a simpler code without passing updateState in createStateupdaters.
from rfcs.
FWIW, it's possible in JS to alter useStateWithUpdaters to take your action object instead of the createStateUpdaters function and then programmatically map each reducer function with updateState. The problem is that "typing" this correctly in flow/typescript isn't straightforward, and i'm not sure it's strictly possible.
from rfcs.
The problem is that "typing" this correctly in flow/typescript isn't straightforward, and i'm not sure it's strictly possible.
Yes, I agree.
Version with useMemo without typescript:
function useStateWithUpdaters(defaultState, rawUpdaters) {
const [state, updateState] = useState(defaultState);
const memoizedUpdaters = useMemo(() => {
const wrappedUpdaters = {};
for (let updaterName in rawUpdaters) { // or can use Object.entries(rawUpdaters).map with Object.fromEntries
wrappedUpdaters[updaterName] = (...params) => {
updateState((prevState) => {
return rawUpdaters[updaterName](prevState, ...params);
});
};
}
return wrappedUpdaters;
}, [rawUpdaters]);
return [state, memoizedUpdaters];
}
const updaters = {
subtract: (prevState, value) => ({ ...prevState, count: prevState.count - value }),
add: (prevState, value) => ({ ...prevState, count: prevState.count + value }),
};
const MyComponent = () => {
const [{ count }, {add, subtract}] = useStateWithUpdaters({ count: 0 }, updaters);
return (
<div>
Count: {count}
<button onClick={() => subtract(1)}>-</button>
<button onClick={() => add(1)}>+</button>
</div>
);
};
from rfcs.
Updated on March 26. 2021. Thanks @bordoley and @KhodeN for helping.
TypeScript version:
interface IObject {
[key: string]: unknown;
}
interface IUpdater<T extends IObject> {
(...params: any[]): T;
}
interface IUpdaterDictionary<T extends IObject> {
[key: string]: IUpdater<T>;
}
interface IWrappedUpdater {
(...params: any[]): void;
}
interface IWrappedUpdaterDictionary {
[key: string]: IWrappedUpdater;
}
// Creates wrapper functions for original updaters and pass current state and arguments to original updaters
function wrapUpdaters<
TState extends IObject,
TUpdaters extends IUpdaterDictionary<TState>
>(rawUpdaters: TUpdaters, updateState: Dispatch<SetStateAction<TState>>) {
return Object.entries(rawUpdaters).reduce((retObject, [method, updater]) => {
retObject[method] = (...params) => {
updateState((prevState) => updater(prevState, ...params));
};
return retObject;
}, {} as IWrappedUpdaterDictionary);
}
function useStateWithUpdaters<
TState extends IObject,
TUpdaters extends IUpdaterDictionary<TState>
>(
defaultState: TState,
rawUpdaters: TUpdaters,
): [TState, IWrappedUpdaterDictionary] {
const [state, updateState] = useState(defaultState);
const wrappedUpdaters = useRef<IWrappedUpdaterDictionary | null>(null);
if (!wrappedUpdaters.current) {
wrappedUpdaters.current = wrapUpdaters<TState, TUpdaters>(rawUpdaters, updateState);
}
return [state, wrappedUpdaters.current];
}
using:
interface ICounterState {
count: number;
}
const updaters = {
subtract: (prevState: ICounterState, value: number) => ({
...prevState,
count: prevState.count - value
}),
add: (prevState: ICounterState, value: number) => ({
...prevState,
count: prevState.count + value
})
};
const MyComponent = () => {
const [{ count }, { subtract, add }] = useStateWithUpdaters(
{ count: 0 },
updaters
);
return (
<div>
Count: {count}
<button onClick={() => subtract(1)}>-</button>
<button onClick={() => add(1)}>+</button>
</div>
);
};
from rfcs.
Thanks!
Splitting complex types to more simpler ones will be more readable.
I don`t know how for others, but for me it is quite difficult to read code like this:
type Tail<TState extends Object, T extends any[]> = T extends [TState, ...infer X] ? X : []; // What is Tail?
type WrappedUpdaters<TState extends Object, TUpdaters extends Updaters<TState>> = {
[m in keyof TUpdaters]: (...args: Tail<TState, Parameters<TUpdaters[m]>>) => TState;
};
To use reduce
β is good idea!
About useMemo for recalculation: https://reactjs.org/docs/hooks-reference.html#usememo
You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to βforgetβ some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components.
Usually do not need to change rawUpdaters in components. Exceptions are very rare. In a reducer code of the useReducer hook, new actions and cases are not added.
So I don't think that is need to add rawUpdaters to the dependencies array and use useMemo.
from rfcs.
Hi, thanks for your suggestion. RFCs should be submitted as pull requests, not issues. I will close this issue but feel free to resubmit in the PR format.
from rfcs.
Related Issues (20)
- onScroll event propagation HOT 5
- [Feature Request]: distinguish "what" and "when" dependencies in useEffect HOT 2
- [Feature Request] Return ref rather than forwardRef HOT 1
- the ability to check if something is function or class or an arrow function HOT 5
- npx-create-react-app creating a folder tempnodejsnpm HOT 2
- [Feature Request] Can we do some Static Analysis for diff with babel οΌ HOT 6
- Improving the RFC workflow process HOT 18
- useIf: Conditional hooks HOT 6
- Improve profiling react applications HOT 1
- Introduce GUI tooling to speed up web application development HOT 1
- [React Server Components] Idea to simplify overall design HOT 11
- psql: could not connect to server: No such file or directory HOT 1
- [Question] The new JSX transform HOT 1
- [Feature Request]: Add array of updated deps indices to `useEffect` hooks arg HOT 1
- [Feature Request]: React Hooks `Equality` **AKA:** `[isEqual]` Callback HOT 3
- Functional Attribute/Prop Node HOT 2
- [Feature Request][eslint-plugin-react-hooks] no-ref-checks, display error when using useRef's return value as condition HOT 1
- [Feature Request]: useStateRef HOT 5
- Typo: 'exiting' might be 'existing' HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from rfcs.