2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React hooksのuseReducerをuseStateから作る

Last updated at Posted at 2019-06-07

はじめに

前の記事で、 useReducer から useState を作ってみましが、逆はできるのだろうかと挑戦してみました。

useReducerを作る

結果的には次のようになりました。

import { useCallback, useMemo, useState } from "react";

export const useReducer = (reducer, initialArg, init) => {
  const [state, setState] = useState(
    init ? () => init(initialArg) : initialArg
  );
  const dispatch = useCallback(
    action => {
      setState(prev => reducer(prev, action));
    },
    [reducer]
  );
  return useMemo(() => [state, dispatch], [state, dispatch]);
};

lazy initializationのあたりが期待通りに実装できているか、確信はありません。useStateの方のシグネチャがシンプルなので、何か違いがあるような気もするのですが。

おわりに

useReducerからuseStateを作って、そのuseStateからまたuseReducerを作って、が永遠にできますね。何か見落としがあったらすみません。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?