Conversation
akmhmgc
commented
Jan 3, 2023
Comment on lines
+7
to
+10
| useEffect(() => { | ||
| fetch("http://localhost:3000/trips") | ||
| .then((response) => response.json()) | ||
| .then((json) => setTrips(json)); |
Owner
Author
There was a problem hiding this comment.
Reactのレンダー(DOMの変更を起こす)後に何らかのアクション(=副作用、Effectと呼ぶ)をおこないたい場合、useEffectを使用する。
コンポーネント内で定義している理由は、stateなどの変数にアクセスすることができるからである。
akmhmgc
commented
Jan 3, 2023
| fetch(url) | ||
| .then((response) => response.json()) | ||
| .then((json) => setTrips(json)); | ||
| }, [url]); |
Owner
Author
There was a problem hiding this comment.
第二引数として監視する変数を指定すると副作用をスキップすることができる
https://ja.reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
akmhmgc
commented
Jan 3, 2023
Comment on lines
+12
to
+14
| useEffect(() => { | ||
| fetchTrips(); | ||
| }, [fetchTrips]); |
Owner
Author
There was a problem hiding this comment.
useEffectの第二引数に関数を指定する場合、関数が定義されると発火する
Reactがrenderを行うたびにコンポーネント内の関数は再定義されるので、useCallbackを使用してrenderのたびにあたらしい関数を作らないようにしないと無限ループとなる。
useCallbackを使用すると関数を毎回作らなくなるが、第二引数を指定するとそれが変化した場合は関数を再定義するようになる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.