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?

[React]前に入力された値を保持する

Posted at

背景

直前に入力された値を保持し、それを処理の中で利用したい箇所があった

実装:

//型アノテーション<string>で文字列型であることを指定、初期値は空文字列('')
//setPreviousStr:previousStrの値を更新するための関数、この関数を呼び出すことで状態を更新可能
//previousStr:前回の文字列の値を保持する状態変数

const [previousStr, setPreviousStr] = useState<string>('');

使用例:

// 設定が解除された際に、以前の文字列の状態を復元するために使用

if (isType(On)) {
  setPreviousStr(Str || ''); // 現在の文字列を保存
  const updatedStr = removeStrs(Str);
  modifyStr(updatedStr);
}

Reactの難しい点とコツ

1. 状態管理が難しい

  • ある処理では値を保持し、ある処理では削除するなど、状態の管理が自由である分適切に制御しないとバグの原因になりやすい。
    • useState / useReducer / useContext などを適切に使い分け、状態を一元管理すると分かりやすくなる。

2. 各処理の条件を厳格に決める

  • 条件が曖昧だと、意図しない副作用が発生しやすく、特に useEffect では依存配列の管理が適当だと無限ループや不要な処理が実行されることがある。
    • 依存配列に入れる値は最小限にする
    • 依存関係が複雑な場合は、カスタムフックに切り出して管理すると分かりやすくなる
    • 不要な再レンダリングを防ぐために useMemo / useCallback を適切に使う

3. 複雑な分岐は関数化する

  • if や switch の分岐が増えすぎると、コードの可読性や保守性が低下する。
    • 条件分岐を関数として切り出す
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?