React Logic: Render & Splitting
Mastering React means moving beyond static pages. You need to control when things render (Conditional Rendering) and how your application bundles code for optimal performance (Lazy Loading & Suspense).
Conditional Rendering in JSX
JSX is mostly JavaScript under the hood, but you cannot put standard block statements (like if/else) directly inside your return statements. Instead, React developers rely heavily on expression-based conditionals.
- Ternary Operator (
condition ? true : false): Ideal for switching between two components. (e.g., Logged in vs Logged out). - Logical AND (
condition && element): Ideal for rendering a component only if a condition evaluates to true, rendering nothing otherwise.
Code Splitting & React.lazy
By default, tools like Vite or Webpack package your entire React app into one large JavaScript file. If users only visit the home page, why force them to download the code for the admin dashboard?
React.lazy() lets you dynamically import a component. React will automatically split your bundle and only request that chunk from the server when the component is actually required to render.
Suspense Boundaries
Network requests take time. When React.lazy() tries to fetch a chunk, React needs to know what to display to the user in the meantime. Enter <Suspense>.
By wrapping your lazy components in a Suspense boundary and providing a fallback prop (like a spinner or skeleton screen), you ensure a seamless UX without the app crashing or going entirely blank.
View Full Architect Transcript+
Remember that Suspense can wrap multiple lazy components. If you have three lazy charts inside a single Suspense boundary, the fallback will display until ALL three charts have loaded. Understanding this grouping is crucial for mastering asynchronous UI patterns in complex React applications.
