Created
January 6, 2019 03:24
-
-
Save audiolion/7ef4fb069b09a26cf7bc1cadfd2e2fee to your computer and use it in GitHub Desktop.
Counterexample to Dan's tweet https://twitter.com/dan_abramov/status/1081595453660106752
This file contains 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
/** | |
* | |
* A very simple refactoring that eliminates the need for a comment "This is the first attempt". | |
* | |
* I am not going to go into the details of why code is better than comments, books like | |
* The Pragmatic Programmer and Fowler's Refactoring provide well-reasoned arguments as to why | |
* this is the case. | |
* | |
*/ | |
// Original | |
function updateSuspenseComponent( | |
current, | |
workInProgress, | |
renderExpirationTime, | |
) { | |
const mode = workInProgress.mode; | |
const nextProps = workInProgress.pendingProps; | |
// We should attempt to render the primary children unless this boundary | |
// already suspended during this render (`alreadyCaptured` is true). | |
let nextState: SuspenseState | null = workInProgress.memoizedState; | |
let nextDidTimeout; | |
if ((workInProgress.effectTag & DidCapture) === NoEffect) { | |
// This is the first attempt. | |
nextState = null; | |
nextDidTimeout = false; | |
} else { | |
// Something in this boundary's subtree already suspended. Switch to | |
// rendering the fallback children. | |
nextState = { | |
timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork, | |
}; | |
nextDidTimeout = true; | |
workInProgress.effectTag &= ~DidCapture; | |
} | |
} | |
// Refactor | |
function updateSuspenseComponent( | |
current, | |
workInProgress, | |
renderExpirationTime, | |
) { | |
function firstAttempt(workInProgress) { | |
return (workInProgress.effectTag & DidCapture) === NoEffect | |
} | |
const mode = workInProgress.mode; | |
const nextProps = workInProgress.pendingProps; | |
// We should attempt to render the primary children unless this boundary | |
// already suspended during this render (`alreadyCaptured` is true). | |
let nextState: SuspenseState | null = workInProgress.memoizedState; | |
let nextDidTimeout; | |
if (firstAttempt(workInProgress)) { | |
nextState = null; | |
nextDidTimeout = false; | |
} else { | |
// Something in this boundary's subtree already suspended. Switch to | |
// rendering the fallback children. | |
nextState = { | |
timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork, | |
}; | |
nextDidTimeout = true; | |
workInProgress.effectTag &= ~DidCapture; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this case, I'd probably use a temp var rather than a func or comment:
const isFirstAttempt = (workInProgress.effectTag & DidCapture) === NoEffect
I tend to use temp vars instead of comments or functions for one liners.