简体   繁体   中英

How does a hook work when called multiple times in a function?

Why does the loading state of true never get logged, but logs when function is async in the follow codesandbox below? When calling the same hook in a function what is happening?

code

codesandbox

function App() {
  const [loadingWithUseState, setLoadingWithUseState] = useState(false);
  const [loadingWithReducer, setLoadingWithReducer] = useReducer(
    (acc, next) => ({ ...acc, ...next }),
    { loadingWithReducer: false }
  );

  const onClickWithUseState = () => {
    setLoadingWithUseState(true);
    setLoadingWithUseState(false);
  };

  const onClickWithReducer = () => {
    setLoadingWithReducer({ loadingWithReducer: true });
    setLoadingWithReducer({ loadingWithReducer: false });
  };

  const onClickWithUseStateAsync = async () => {
    setLoadingWithUseState(true);
    await delay();
    setLoadingWithUseState(false);
  };

  const onClickWithReducerAsync = async () => {
    setLoadingWithReducer({ loadingWithReducer: true });
    await delay();
    setLoadingWithReducer({ loadingWithReducer: false });
  };

  useEffect(() => {
    console.log("loadingWithUseState changed to", loadingWithUseState);
  }, [loadingWithUseState]);

  useEffect(() => {
    console.log("loadingWithReducer changed to", loadingWithReducer);
  }, [loadingWithReducer]);

  console.log("re-render", { loadingWithUseState, ...loadingWithReducer });

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={onClickWithUseState}>
        {" "}
        trigger load with useState{" "}
      </button>
      <button onClick={onClickWithReducer}>
        {" "}
        trigger load with useReducer{" "}
      </button>
      <button onClick={onClickWithUseStateAsync}>
        {" "}
        trigger load with async useReducer{" "}
      </button>
      <button onClick={onClickWithReducerAsync}>
        {" "}
        trigger load with async useReducer{" "}
      </button>
    </div>
  );
}

PS i want to build a mental model of what happens when you call multiple hooks together

When you set state, ReactJS batches the state updates for performances reasons. So, when you call setLoadingWithUseState(true) followed by setLoadingWithUseState(false) , React will batch those two together, so you won't see the first update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM