Hi everyone 👋
I’d like to get some guidance / best-practice clarification regarding component structure in React, especially in the context of RTK Query usage.
In the RTK Query docs and examples, I see that some components are written using a single return, with conditional logic that assigns JSX to a variable (e.g. content) before returning it, like here is the second example of this section.
Example (simplified):
export const PostsList = () => {
const {
data: posts = [],
isLoading,
isFetching,
isSuccess,
isError,
error
} = useGetPostsQuery()
let content: React.ReactNode
if (isLoading) {
content = <Spinner text="Loading..." />
} else if (isSuccess) {
content = <Posts posts={posts} />
} else if (isError) {
content = <div>{error.toString()}</div>
}
return <section>{content}</section>
}
An alternative pattern that many React developers use is early returns / multiple returns, for example:
if (isLoading) return <Spinner />
if (isError) return <Error />
if (isSuccess) return <Posts posts={posts} />
return null
Questions
-
Is there a recommended or preferred pattern between:
- multiple early returns
- a single
return with conditional JSX assignment?
-
Are there any readability, maintainability, or performance considerations that justify choosing one approach over the other?
-
Is the single-return style used in RTK Query examples mainly for teaching/consistency purposes, or is it considered a best practice?
-
I’m particularly interested in guidance for production codebases and team conventions.
I’m particularly interested in guidance for production codebases and team conventions.
Thanks in advance for your insights 🙏
Hi everyone 👋
I’d like to get some guidance / best-practice clarification regarding component structure in React, especially in the context of RTK Query usage.
In the RTK Query docs and examples, I see that some components are written using a single return, with conditional logic that assigns JSX to a variable (e.g. content) before returning it, like here is the second example of this section.
Example (simplified):
An alternative pattern that many React developers use is early returns / multiple returns, for example:
Questions
Is there a recommended or preferred pattern between:
returnwith conditional JSX assignment?Are there any readability, maintainability, or performance considerations that justify choosing one approach over the other?
Is the single-return style used in RTK Query examples mainly for teaching/consistency purposes, or is it considered a best practice?
I’m particularly interested in guidance for production codebases and team conventions.
I’m particularly interested in guidance for production codebases and team conventions.
Thanks in advance for your insights 🙏