0
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 3 years have passed since last update.

React備忘録

Last updated at Posted at 2020-12-16

ReactHooksについて

・useState
・useReducer
・useContext
・action.js
・useEffect
・combineReducers(Redux)
適宜追加していきます。

useState

const [state, setState] = useState(initialState);

のような形で、左側は自分で命名したstate、右側はsetの次は大文字にする。右側のset~を使ってstateの値を更新する。useStateの()には初期値を設定する。

useReducer

useReducerを用いることで、ステート更新関数をステート非依存にすることを強制できます。実際のアプリ開発においては、アプリが複雑化するにつれて、あるステートと別のステートが関わりを持ち始めるかもしれません。

App.jsx
 const initialState = {
    events: [],
    operationLogs: []
  };
  const [state, dispatch] = useReducer(reducer, initialState);
reducers/event.js
import { CREATE_EVENT, DELETE_ALL_EVENTS, DELETE_EVENT } from "../actions";
const events = (state = [], action) => {
  switch (action.type) {
    case CREATE_EVENT:
      const event = { title: action.title, body: action.body };
      const length = state.length;
      const id = length === 0 ? 1 : state[length - 1].id + 1;
      return [...state, { id, ...event }];
    case DELETE_EVENT:
      return state.filter((event) => event.id !== action.id);
    case DELETE_ALL_EVENTS:
      return [];
    default:
      return state;
  }
};
export default events;
components/Event.jsx
const addEvent = (e) => {
    e.preventDefault();
    dispatch({
      type: CREATE_EVENT,
      title,
      body
    });
    dispatch({
      type: ADD_OPERATION_LOG,
      description: "イベントを作成しました",
      operatedAt: timeCurrentIso8601
    });
    setTitle("");
    setBody("");
  };

コードの説明

App.jsx
const [state, dispatch] = useReducer(reducer, initialState);
を宣言します。そうすることで現在の state dispatchメソッドとペアにして返します。
components/Event.jsxのfunction内でdispatch呼ぶことでtypeとパラメーターをreduers/event.jsにactionとして渡します。
こうして渡ってきたactionをreduers/event.jsないでcase文で分岐させます。
現在stateにeventsというオブジェクトがあり、その中にデータとして配列で格納されています。

useContext

useContextを使うメリットはpropsによるバケツリレーをしなくて済むので、不要なコードを書かなくてよくなる。

contexts/AppContext.js
import { createContext } from "react";
export const AppContext = createContext();
App.jsx
return (
    <>
      <AppContext.Provider value={{ state, dispatch }}>
        <EventForm />
        <Events />
        <OperationLogs />
      </AppContext.Provider>
    </>
  );
components/Events.jsx
import { AppContext } from "../contexts/AppContext";
export const Events = () => {
  const { state } = useContext(AppContext);

コードの説明

contexts/AppContext.jsでcreateContext();を宣言します。
そして、App.jsxAppContext.Provider value={{ state, dispatch }}という形で
以前はcomponentsごとに書いていたpropsを一括してAppContextとして記述します。
そうすることで、components内でstateだけを呼びたいのであれば
const { state } = useContext(AppContext);と記述して
両方呼びたいのであれば
const { state, dispatch } = useContext(AppContext);と記述する。
useContextを使うことでcomponents内でpropsとして渡さなくてもよくなる。

useEffect

https://sbfl.net/blog/2019/11/12/react-hooks-introduction/
が非常にわかりやすいです。
クリーンナップ関数を設定する理由はアンマウントされた際に前回のuseEffectが残ったまま、重複することになるので、クリーンナップ関数で消してあげる為です。

0
1
1

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
0
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?