1
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 Hooksメモ

Posted at

React hooksメモ

□useState
stateを管理するフック

const stateTest = () => {
  // countに0を入れて初期化。setCountで新しい値の代入
  const [count, setCount] = useState(0) 
  return <div onClick={() => setCount(count+1)}>{count}</div>
};

□useRef
ref要素を保持するフック。useStateのref版

const refTest = () => {
  const refCont = useRef(null);
  useEffect(() => {
    refCont.current.innerText = 'tesutodesu!';
  }, []);
  return <div ref={refCont}></div>
};

□useReducer
useState の代替品です。(state, action) => newState という型のリデューサ (reducer) を受け取り、現在の state を dispatch メソッドとペアにして返します。

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

□useEffect
副作用を実行するフック。Reactのレンダリング後にしたい処理をする
APIとの通信やDOM操作を行う場合などに使用

const effectTest = () => {
  const [cont, setCont] = useState('');
  useEffect(() => {
    fetch(
      '/api/endpoint',
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `access_token`,
      },
    ).then(
      (response) => response.json()
    ).then(
      (json) => setContent(json.cont)
    );
  });
  return <div>{cont}</div>
};

□useMemo
関数の結果をキャッシュして、次回以降のアクセス時にはキャッシュから値を取得
第二引数の値が変わった場合、再キャッシュする

const memoTest = (props) => {
  const val = useMemo(() => testfunc(props.id), [props.id]);
  return <div>{val}</div>
};

□useCallback
useMemoは関数の結果としての関数もキャッシュできるが、その場合はこちらを使用するのが楽
状態によって変わる関数の場合は、引数にその引数の指定が必要

□useLayoutEffect
DOMの変更があった後に同期的に副作用が呼び出されます

□useContext
stateをグローバルに管理するフック
複数のコンポーネントからstateを呼び出すときに使用

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