Giter Site home page Giter Site logo

Comments (10)

bordoley avatar bordoley commented on May 27, 2024 2

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.

bordoley avatar bordoley commented on May 27, 2024 1

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.

KhodeN avatar KhodeN commented on May 27, 2024 1

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.

sergeysibara avatar sergeysibara commented on May 27, 2024

@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.

sergeysibara avatar sergeysibara commented on May 27, 2024

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

from rfcs.

bordoley avatar bordoley commented on May 27, 2024

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.

sergeysibara avatar sergeysibara commented on May 27, 2024

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.

sergeysibara avatar sergeysibara commented on May 27, 2024

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.

sergeysibara avatar sergeysibara commented on May 27, 2024

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.

gaearon avatar gaearon commented on May 27, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.