2
0

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でやってしまいがちな、propsを更新したのにuseStateの値が更新されないぞという話。

Posted at

「あれれ~? props を更新したのに、子componentのuseStateの値が更新されないぞ~??:nerd:

こんな感じになっていませんか?

export const ParentComponent: React.FC = () => {
  const [count, setCount] = useState(0);

  function handleInput(e: React.ChangeEvent<HTMLInputElement>) {
    setCount(Number(e.currentTarget.value));
  }

  return (
    <div>
      <input
        type="number"
        defaultValue={count}
        name="parent-value"
        onChange={handleInput}
      />
      <ChildComponent parentCount={count} />
    </div>
  );
};

const ChildComponent: React.FC<{ parentCount: number }> = props => {
  const { parentCount } = props;
  const [count] = useState(parentCount);
  return (
    <div>
      <span>update されない </span>
      {count}
    </div>
  );
};

useStateの初期値にpropsを渡すパターンですね。恥ずかしながら、自分もときどきやっちまいます:sweat:
理由は、単純に ChildComponentがrerenderされてるだけなので、stateの値を保持しているからです。

こんなときはuseEffectを使ってupdateします。

const ChildComponent: React.FC<{ parentCount: number }> = props => {
  const { parentCount } = props;
  const [count, setCount] = useState(parentCount);

  useEffect(() => {
    setCount(parentCount);
  }, [parentCount]);

  return (
    <div>
      <span>update できる </span>
      {count}
    </div>
  );
};

当たり前じゃんってことなのですが、よく聞かれるし自分でもやってしまいがちなのでまとめました(^_^;)

サンプルコード

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?