Rules Hub
Coding Rules Library
Prefer components over render helper functions
Avoid using helper functions to return JSX; extract them into standalone React components for better debugging and performance.
Bad example
| 1 | function renderStatusDot(status: string) { |
| 2 | return <div className={`dot dot--${status}`} />; |
| 3 | } |
| 4 |
|
| 5 | export const InvoiceItem = ({ status }: { status: string }) => { |
| 6 | return ( |
| 7 | <div className="invoice-item"> |
| 8 | {/* Helper function call instead of Component */} |
| 9 | {renderStatusDot(status)} |
| 10 | <span>Invoice Info</span> |
| 11 | </div> |
| 12 | ); |
| 13 | }; |
Explanation (EN)
Using a helper function (`renderStatusDot`) to return JSX bypasses React's component system. It doesn't show up in React DevTools, cannot use hooks efficiently, and treats the returned JSX as part of the parent's render output rather than a distinct unit.
Objašnjenje (HR)
Korištenje pomoćne funkcije (`renderStatusDot`) za vraćanje JSX-a zaobilazi Reactov sustav komponenti. Takva funkcija se ne prikazuje u React DevTools, ne može efikasno koristiti hookove i tretira vraćeni JSX kao dio roditeljskog rendera umjesto kao zasebnu cjelinu.
Good example
| 1 | const StatusDot = ({ status }: { status: string }) => { |
| 2 | return <div className={`dot dot--${status}`} />; |
| 3 | }; |
| 4 |
|
| 5 | export const InvoiceItem = ({ status }: { status: string }) => { |
| 6 | return ( |
| 7 | <div className="invoice-item"> |
| 8 | {/* Usage as a proper React Component */} |
| 9 | <StatusDot status={status} /> |
| 10 | <span>Invoice Info</span> |
| 11 | </div> |
| 12 | ); |
| 13 | }; |
Explanation (EN)
Extracting the logic into a named component (`StatusDot`) ensures it appears correctly in the component tree, supports hooks, and can be memoized if necessary. It improves readability and standardizes the codebase.
Objašnjenje (HR)
Izdvajanje logike u imenovanu komponentu (`StatusDot`) osigurava da se ona ispravno prikazuje u stablu komponenti, podržava hookove i može se memoizirati ako je potrebno. To poboljšava čitljivost i standardizira kod.