Closed7

Don't over useState

牛嶋一登牛嶋一登

fetch()でデータをとってきて、useStateする。
ものすごい既視感。

const [data, setData] = React.useState(null)
  const [categories, setCategories] = React.useState([])

  React.useEffect(() => {
    async function fetch() {
      const response = await fetchData()
      setData(response.data)
    }

    fetch()
  }, [])

  React.useEffect(() => {
    if (data) {
      setCategories(computeCategories(data))
    }
  }, [data])
牛嶋一登牛嶋一登
- The page loads, categories are X
- User clicks the button, categories are Y
- If the data fetching re-executes, say, because we are using react-query, which has features like automatic re-fetching when you focus your tab or when you re-connect to your network (it's awesome, you should give it a try), the categories will be X again.

確かに。
setCategories はいつでも呼び出せるけど、 fetch() が実行されうる可能性がある限り、更新されないことがあり得るのか。

牛嶋一登牛嶋一登
-  const [categories, setCategories] = React.useState([])
+  const categories = data ? computeCategories(data) : []

なるほど。
categoriesはdataから取れるから、そもそもuseStateする必要すらないのか

このスクラップは2023/12/20にクローズされました