LoginSignup
4
1

More than 3 years have passed since last update.

React Hook で管理する値の更新について

Posted at

はじめに

ReactHooksで配列などで管理している値を変更したい際の方法をまとめました。

配列の更新

配列をHooksで管理している際は以下のように変更できます。

配列の最後に要素をプッシュ part1

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

const newArray = Array.from(initialArray);
newArray.push(newValue);
setSampleArray(newArray);

配列の最後に要素をプッシュ part2

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

setSampleArray(oldArray => [...oldArray, newValue]);

オブジェクトの更新

オブジェクトをHooksで管理している際は以下のように変更できます。

オブジェクトの最後に要素をプッシュ/更新する part1

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

const newObj = Object.assign({}, initialArray);
newObj[currentOrNewKey] = newValue;
setSampleObject(newObj);

オブジェクトの最後に要素をプッシュ/更新する part2

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

setSampleObject(oldState => ({ ...oldState, currentOrNewKey: newValue}));

オブジェクトの最初に要素をプッシュ/更新する

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

setSampleObject(oldState => ({currentOrNewKey: newValue}, ...oldState));

オブジェクトの配列の最後に要素をプッシュ/更新する

sample.js
const [sampleArray, setSampleArray] = useState(initialArray);

setSampleArray(oldState => [...oldState, {currentOrNewKey: newValue}]);
4
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
4
1