1
2

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.

useState変更前の値を保持する

1
Last updated at Posted at 2023-01-01

やり方

useRefを使用して、変更前のnameを保持する

import React, {
  useState,
  useEffect,
  useRef
} from 'react';

export default function App() {
  const [name, setName] = useState('');
  const prevName = useRef('');

  useEffect(() => {
    prevName.current = name;
  }, [name]);

  return (
    <>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <div>
        My name is {name} and it used to be{' '}
        {prevName.current}
      </div>
    </>
  );
}

参考ビデオ:https://youtu.be/t2ypzz6gJm0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?