Skip to content

セクション8: Fetching Data & useEffect - #1

Open
akmhmgc wants to merge 8 commits into
mainfrom
section-8
Open

セクション8: Fetching Data & useEffect#1
akmhmgc wants to merge 8 commits into
mainfrom
section-8

Conversation

@akmhmgc

@akmhmgc akmhmgc commented Jan 3, 2023

Copy link
Copy Markdown
Owner
  • useEffectについて
  • useCallbackについて

Comment thread src/components/TripList.js Outdated
Comment on lines +7 to +10
useEffect(() => {
fetch("http://localhost:3000/trips")
.then((response) => response.json())
.then((json) => setTrips(json));

@akmhmgc akmhmgc Jan 3, 2023

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reactのレンダー(DOMの変更を起こす)後に何らかのアクション(=副作用、Effectと呼ぶ)をおこないたい場合、useEffectを使用する。
コンポーネント内で定義している理由は、stateなどの変数にアクセスすることができるからである。

参考:https://ja.reactjs.org/docs/hooks-effect.html

fetch(url)
.then((response) => response.json())
.then((json) => setTrips(json));
}, [url]);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

第二引数として監視する変数を指定すると副作用をスキップすることができる

https://ja.reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

Comment on lines +12 to +14
useEffect(() => {
fetchTrips();
}, [fetchTrips]);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffectの第二引数に関数を指定する場合、関数が定義されると発火する
Reactがrenderを行うたびにコンポーネント内の関数は再定義されるので、useCallbackを使用してrenderのたびにあたらしい関数を作らないようにしないと無限ループとなる。

useCallbackを使用すると関数を毎回作らなくなるが、第二引数を指定するとそれが変化した場合は関数を再定義するようになる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant