Skip to content

Conversation

@kangaroooh
Copy link

Current behaviour
When rendering a component, if I call the dispatch (setState) function of useReducer before I actually call useReducer, it will trigger the component to be rerendered.
This behaviour is demonstrated here, the custom hook's code is copied bellow.

Suggested behaviour
In the current implementation, dispatched actions (and mostly the ones triggered during the render phase) are handled inside useReducer. If the dispatch function is called before useReducer, we don't have to wait to rerender to handle this action.
This new behaviour is demonstrated in the current Pull Request.
I'm not expecting a negative effect because hooks are currently meant to be called always in same order and not conditionally.

Motivation
I came to this change trying to implement a custom hook useDerivedState:

const useDerivedState = (computeDerivedState, inputs, initialState = null) => {
  const setStateRef = useRef(null);
  useMemo(() => {
    if (setStateRef.current) {
      const setState = setStateRef.current;
      setState(prevState => {
        const newState = computeDerivedState(prevState);
        return newState !== undefined ? newState : prevState;
      });
    }
  }, inputs);
  const stateStuff = useState(() => {
    let state = initialState;
    if (typeof state === "function") {
      state = state();
    }
    return computeDerivedState(state);
  });
  [, setStateRef.current] = stateStuff;
  return stateStuff;
};

@softagram-bot
Copy link

Softagram Impact Report for pull/15 (head commit: ff4e7fb)

⭐ Visual Overview

Changed elements and changed dependencies.
Changed dependencies - click for full size
Graph legend
(Open in Softagram Desktop for full details)

⭐ Change Impact

How the changed files are used by the rest of the project
Impacted files - click for full size
Graph legend
(Open in Softagram Desktop for full details)

💡 Insights

  • Co-change Alert: You modified ReactFiberHooks.js. Often ReactHooks-test.internal.js (src/tests) is modified at the same time.

📄 Full report

Give feedback of this report to [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants