reactjs / rfcs

RFCs for changes to React

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is useReducer an overengineering?

sergeysibara opened this issue · comments

I suppose that direct calls to functions will be simpler for use than construction dispatch + actions + function-reducer.
What are the advantages of dispatch + actions + function-reducer vs direct calls to actions (functions) like my example below?

useReducer alternative (updated on March 26. 2021. Thanks @bordoley and @KhodeN for helping):

// Creates wrapper functions for original updaters and pass current state and arguments to original updaters
const wrapUpdaters = (rawUpdaters, updateState) => {
  const wrappedUpdaters = Object.entries(rawUpdaters).reduce((retObject, [method, updater]) => {
    retObject[method] = (...params) => {
      updateState((prevState) => updater(prevState, ...params));
    };
    return retObject;
  }, {});

  return wrappedUpdaters;
};

const useStateWithUpdaters = (defaultState, rawUpdaters) => {
  const [state, updateState] = useState(defaultState);

  const wrappedUpdaters = useRef(null);
  if (!wrappedUpdaters.current) {
     wrapUpdaters.current = wrapUpdates(rawUpdaters, updateState);
  }

  return [state, wrappedUpdaters.current];
}

using useStateWithUpdaters hook (updated on Jan 22. 2021):

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>
  );
};
commented

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>
    </>
  );
}


@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>
    </>
  );
}
commented

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>;
}

Thanks!
But I would to get a simpler code without passing updateState in createStateupdaters.

commented

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.

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>
  );
};

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>
  );
};

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];
}

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.

commented

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.