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.

UseRefのように配列を扱う

Last updated at Posted at 2021-12-11

はじめに

ReactのuseRefは、React Hooksで参照するための変数を定義する関数である。ところが、この変数には配列やオブジェクトを入れることができない。useRefのように配列を扱うには、useReducerを用いる。

sample.js
import React, {useRef, useReducer} from 'react';

// 配列をsomeArray、操作する関数をdispatchとそれぞれ定義。
// useReducerの引数はReducerFunc、初期配列
const [someArray, dispatch] = useReducer(reducerFunc, [])

//reducerFuncが更新後の配列を返す。
function reducerFunc(state, action) {
    if (action.type === "add") {
        return [...state, action.value]
    } else {
        throw `Invalid type:${action.type}`
    }
}

//実際に追加するときは、配列の操作関数であるdispatchにreducerFuncが読めるオブジェクトを渡す。
// この例では文字列"some_value"が配列に追加される。
dispatch({
    type: "add",
    value: "some_value"
}}

補足

dispatchをpropsで渡すことで、子要素からも配列の値を変更することができる。

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