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 5 years have passed since last update.

【React】初回レンダリングを回避したい

2
Last updated at Posted at 2021-06-07

初回レンダリングされる

以下を読み込むと、初回レンダリングが走ってしまい、「1回押された」と表示されてしまいます。 本来はbuttonが押されたときのみ、処理をさせたい。。。!!

なので、初回レンダリング時に読み込ませないようにします。

Hoge.jsx
import React, { useState} from "react";

export const Hoge= () =>{
  const [count,setCount] = useState(0);

  const handleHoge= () =>  {
      setCount(count+1)
  }

  return(
    <div>
        <div>{count}回押された</div>
        <button onClick={() => handleHoge()}>HOGEButton</button>
    </div>
  )
}

解決策

初回レンダリングかどうかのフラグを持たせて、制御する方法です。
Hoge.jsx
import React, { useRef,useState,useEffect } from "react";

export const Hoge= () =>{
  const [count,setCount] = useState(0);
  const renderFlgRef = useRef(false)

  useEffect(() => {
    console.log("初回レンダリング")
    renderFlgRef.current = true
  },[])

  const handleHoge= () =>  {
    if (renderFlgRef.current){
      setCount(count+1)
    }
  }

  return(
    <div>
        <div>{count}回押された</div>
        <button onClick={() => handleHoge()}>HOGEButton</button>
    </div>
  )
}

参考

https://stackoverflow.com/questions/55075604/react-hooks-useeffect-only-on-update

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?