-
-
Save markerikson/47fff93c92286db72b22bab5b02e2da3 to your computer and use it in GitHub Desktop.
// See https://blog.isquaredsoftware.com/presentations/react-redux-ts-intro-2020-12/#/36 for slides | |
// My basic render function structure: | |
function RenderLogicExample({ | |
someBoolean, // 1) Destructure values from `props` object | |
someList, | |
}) { | |
// 2) Declare state values | |
const [a, setA] = useState(0); | |
const [b, setB] = useState(0); | |
// 3) Render any dependent items into temporary variables, | |
// such as conditional components or lists | |
const conditionalComponent = someBoolean ? ( | |
<SomeConditionalComponent /> | |
) : null; | |
const listItems = someList.map(item => ( | |
<ListItem key={item.id} item={item} /> | |
)); | |
// 4) Use a single JSX structure filled with content | |
return ( | |
<div> | |
<div> | |
A: {a}, B: {b} | |
</div> | |
{conditionalComponent} | |
{listItems} | |
</div> | |
); | |
} |
You don't need any other method returning UI elements rather than the render one. If you need to split the render method, then you should probably create another Component instead. Scrolling class methods to change some UI behavior is not funny at all...
Nice.
minor remark, I would add index to the listitem
Defining a named function or variable in the render function is no different to just running the map directly in the render function. You are still declaring a new function every time render fires. Declaring it on the class, or outside of the functional component will use an existing reference to the function and improve performance in some cases, although not required for faster prototyping until an optimization step (if at all needed).
Adding index to listitem is an anti-pattern that will create mysterious problems down the track (unless you are familiar with these problems, in which case you already know to protect against it). Instead, the key should be set to a consistent value derived from the mapped items (ID, or a concatenated string of one/two string fields that appear in the object guaranteed to be stable/unique in this set of data).
https://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd
so no render props ?
awesome, as a self-taught developer I'm always hesitating on simple things that I already know and do. Just reading codes from pros make me more confident about my thoughts and the style of the code I write, so much appreciated 💯
I keep all my control flow inline, but calculations outside. I like it all inline so I know why something is or isn't rendering without bouncing around the file. Every variable is an abstraction with a cost of indirection. Not every branch deserves a name, just like css class names, naming fatigue slows me way down, and the names usually don't help with understanding anyway.