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

More than 1 year has passed since last update.

【React】 UseEffect を使用して、コンポーネントが呼ばれた最初だけ実行する処理を実装

Last updated at Posted at 2021-12-08

今回のテスト
ボタンをクリックすると、コンポーネントが呼ばれる最初だけ、ある処理を実行する。

■以下前提のコード

sample.js
import React,{useState,useEffect} from 'react'
const sample= () => {
}
export default sample

■以下ボタンを実装

sample.js
import React,{useState,useEffect} from 'react'

const sample = () => {
    return (
        <div>
            <button onClick={()=> setCnt(prevCnt=>prevCnt+1)}>Click Count {cnt}</button>          
        </div>
    )
}
export default sample

■以下stateとstateを更新する関数(setCnt)を実装。※constの最後の,[]が一度だけ呼び出す肝。

sample.js
import React,{useState,useEffect} from 'react'

const sample = () => {
    const [cnt,setCnt] = useState(0)
    useEffect(()=> {
        console.log("useEffect invoked")
    },[])
    return (
        <div>
            <button onClick={()=> setCnt(prevCnt=>prevCnt+1)}>Click Count {cnt}</button>          
        </div>
    )
}
export default sample

■結果
ブラウザを開くとブラウザのコンソールに「useEffect invoked」と1度だけ表示される。ボタンをクリックしても、それ以降表示されない。

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