LoginSignup
8
3

More than 1 year has passed since last update.

【React】React クイズ!!

Last updated at Posted at 2021-06-15

はじめに

いきなりですがクイズです!!
React.js初心者向けのクイズを3問考えました。
クイズは、Reactの関数コンポーネントを用いたstateとライフサイクルに関する問題です。

クイズの答えは、記事の最後に記載しています。

第1問: 以下の様なコードを実行した場合、どのような順番に実行されるでしょうか?

A〜Cの回答で答えよ。

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

const Button = () => {

  const [count, setCount] = useState(0)

  useEffect(()=> {
    // ①
    console.log("")

    return ()=> {
    // ②
      console.log("")
    }
  }, [])

  return (
    // ③
    <div>
      {count}
    </div>
  )
}

export default Button

回答:
A. ① → ② → ③
B. ③ → ① → ②
C. ② → ③ → ①

第2問: 以下の様なコードがあった場合、countの値はいくつになるでしょうか?

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

const Button = () => {

  const [count, setCount] = useState(0)

  useEffect(()=> {

    setCount(count + 100)
    setCount(count + 1000)
    setCount(count + 10000)
    setCount(count + 10000)
    setCount(count + 100000)
    setCount(count + 1000000)

    return ()=> {
      console.log("clean up")
    }
  }, [])

  return(
    <></>
  )
}

export default Button

回答:
A. 1111100
B. 100
C. 1000000
D. 1121100

第3問: 以下の様なコードがあった場合、初回マウント時の正しい実行順序を答えなさい。

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

const Button = () => {

  const [count1, setCount1] = useState(0)
  const [count2, setCount2] = useState(0)
  const [count3, setCount3] = useState(0)


  useEffect(()=> {
    // ①
    console.log("update count1")
  }, [count1])

  useEffect(()=> {
    // ②
    console.log("update count3")
  }, [count3])

  useEffect(()=> {
    // ③
    console.log("update")
    return ()=> {
      console.log("clear")
    }
  }, [])

  useEffect(()=> {
    // ④
    console.log("update count2")
  }, [count2])

  return(
    <></>
  )
}

export default Button

回答:
A. ③ → ① → ④ → ②
B. ① → ② → ③ → ④
C. ③ → ① → ② → ④
D. ④ → ③ → ② → ①

-

-

-

-

-

-

-

-

-

-

-

問題の答え

  • 第1問の答え: B. ( ③がclassにおけるrender()、①がcomponent Did Mount()、②がcomponent will unmount()に該当する。)

  • 第2問の答え: C.

  • 第3問の答え: B. コードは上から順番に実行されます。component Did Mount()後のアップデートでは、①→②→④の順に実行されます。

8
3
2

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
8
3