React docs on useEffect
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
The docs have an example about using useEffect with cleanup, here.
If I carry out the sequence, then I would get
run effect -> subscribe to update from ChatApi -> setIsOnline -> cleanup -> run effect -> subscribe to update from ChatApi -> setIsOnline
I am unsure as to why this does not lead to an infinite loop without use of the dependency array?
One understanding / theory that I have is:
The first time the subscription cause setIsOnline(true). Next time (after one cycle of unsubscribe/effect), the setIsOnline gets argument as true and hence further update to the component does not occur. This is assuming that this form of setIsOnline does not re-render if the isOnline has not changed (it is still true).
I am curious as to why the piece of code is correct.
Here it is as copied from the useEffect documentation
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked useEffect documentation example and review the described subscription, cleanup, and setIsOnline sequence. Clarify whether the example needs an explanation of its rerender behavior or a revised example, then update the documentation so the expected effect lifecycle and completion criteria are explicit.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100