system-design-react-code-examples
A curation of code examples and in depth technical implementation approaches to solve the common frontend system design issues in React.
Target Audience
- advanced beginner/intermediate developers wishing to get better technical understanding
- developers exploring how to do handle technical things in their own projects.
- for my own reference as I need something like this for my own learning.
Philosophy
The philosophy behind this endeavour is to document as much as possible a practical guide for someone looking to level-up fast/ implement things.
โTalk is cheap. Show me the code.โ โ Linus Torvalds
Architecture Deep dive
- Rebuilding our tech stack for the new Facebook.com
- Front-End Performance Optimization with Accelerated Compositing Part 1
- Front-End Performance Optimization with Accelerated Compositing Part 2
- SSR-based Optimization of Double 11 Virtual Venue โ A More Complex Rendering Architecture
- React Philosophies
- idiomatic.js
- Client-Side Architecture Basics
- CSS Triggers - what forces layout/reflow
- The Web Browser Internals
- A (Mostly) Complete Guide to React Rendering Behavior
Engineering Design
- Team size
- User base
- Knowledge base
- Compliance/Governance
- User/Client expectations
- Open source vs proprietary
- Documentation / PRD
- Future Roadmaps
High Level Design
- Platform identification
- SPA vs MPA
- SSR, SSG, CSR
- Tech stack
- Search Engine Optimization
- CI/CD
- User Experience
- A/B testing
- MVP planning
- Server Side Architecture
- Security
- State Management
- Internationalization - example
- E2E testing
- Tools Integration
- Authentication & Authorization
- Quality Assurance & Control
- User role management - example
Low Level Design
- Code/Folder architecture
- Desktop/Mobile first approach
- System breakdown
- Component Design
- Form development
- Storage management
- Using localForage
- redux-persist - code
- API Design
- Instrumentation
- Design system
- Routing management
- Example pattern - code
- CSS optimizations - Code-splitting
- Lazy loading of modules
- Accessibility
- Image optimizations
- Pagination, Debouncing, Throttling
- Performance: FCP, LCP, TTI, CLS
- Versioning - example - code
- Unit testing
- Authentication and authorization Management
High Level Design details
Product Requirement Document (PRD) / Design Document
- Identify Scope/Requirement
- Review your understanding with stakeholders
Discuss about Design/Wireframe
- Think like an architect.
- We should not consider team bandwidth, capacity and time.
- Discuss about Edge cases.
- Robustness: Handle SPOF (Single Point of Failure) ex: Monitoring, Logging
Identify Business
- Is it B2B (business-to-business)?
- Is it B2C (business-to-consumer)?
- Is it Internal Product?
- Is it Customer facing product?
Identify Platform
- Desktop
- Mobile
- Tablet
Identify Users (Know your audience)
- Conduct surveys
- Discuss about Location and Devices
- Internet speed
- End Users knowledge base (ex: Technical user)
- Pilot Product (sometimes to understand audience)
Identify Design Approach
- Responsive vs Adaptive design
- Desktop first vs Mobile first
Identify APIs
- Rest APIs / Graph APIs / RPC
- JSON / Protocol buffers
Role based management
- Large system needs roles based access and permissions
- Authentication and Authorization
- Read/Write/View Permissions
- Discuss about Routes/Component access
Identify Right Platform (compare frameworks based on the use case)
- Single Page Applications (Unsuitable for Blogs/News based products)
- No reloading of a page at navigation
- No SEO
- Multi Page Applications
- Reloading of a page at every page navigation.
- Progressive Web Applications
- Provides offline support and native like functionality.
- Examples of PWA
- Server Side Rendering
- Better SEO
- Important points to discuss:
- Are users on mobile?
- Is SEO needed?
- Is SPA enough?
- Is PWA enough? (Service worker, Web Worker)
- Compare SSR / SSG / CSR
- Any Pricing model? (optional) - Subscriptions based, Paid APIs
- Will my app be Frontend heavy? (or backend heavy)
- Do I have resources for this skill?
- Is your application Canvas (or SVG) heavy? (Figma, Draw.io) - example
- Is your application webRTC heavy? (Video streaming) - example
Identify User Flow
- Discuss vision of a product.
- Do we need to build from scratch or we can leverage some existing functionalities
- Discuss about authentication and authorization (Google auth / OAuth)
- Interact with the Product manager to understand the scope before designing the application.
- Discuss happy scenarios.
- Discuss edge cases.
- Discuss failing scenarios
Identify MVP (Minimum Viable Product)
- Problem -> Solution -> Build MVP -> MVP to Customers
- Discuss MVP phase with product manager
- Discuss roadmaps and divide product in milestones
- After MVP release there can be a slight change in design/approach to make the product better
Volume of Operations
- Discuss about the end users of the product
- Observe the data in something like Google Analytics for split by device/location/OS etc in production later.
- Identify QPS (Queries per second)
- Monitor throughput of the web server/ web application server - benchmark for reference
- Discuss about Load testing/Stress testing
- Inject analytics in application (ex: Google analytics, Sentry, NewRelic)
- For cost-effectiveness instead of using ready-made solution, can define our events, using Kafka to stream the events to a backend server and use a Grafana dashboard if required.
- Analytics data helps us to scale the system
SEO (Search Engine Optimization)
- Crawling
- Use of Heading tags
- Semantic tags - HTML Reference - Example
- Site Ranking
- Sitemap
- Meta Keywords - Example
- Organic approach vs Inorganic approach
- Use of alt tags
- 301 Redirects (bad for SEO)
- Robots.txt - Example
- Open graph protocol for social graph - Example
Component Based Design
- Component wise deployment cycle (CI/CD)
- Monolith vs Microservice architecture
- Micro Frontend (independent dev & deployment for scalability)
- Static components vs Dynamic components
- IFrame/Shell approach
State Management
- How to maintain state through the application?
- How to manage users' data?
- State management Libraries (Redux, Flux, NgRX)
-
- Redux Architecture
- Redux-saga
- Example Codebase -react-crwn-cothing-ecom
- Example Codebase -fakeflix
- RxJS
- Redux Thunk
Handling APIs
- Polling (Short and Long) library
- Web Sockets (Real-time) (ex: chat, shared editors)
- Batch requests
- GraphQL
- Caching GET APIs (Middleware concepts to cache response) - guide
- Server-Sent Events (SSE) - guide
- Graceful handling(eg. X number of retries before giving up(linear, exponential backoff etc)
- Error Handling
- error handling with async/await pattern - See the section Async Logic and Side Effects
- Others
Optimizing Images
- Add alt attributes (Images should be descriptive for SEO)
- Load images based on screen size (img srcset)
- Image compression (ex: JPEG 2000)
- Image sitemaps
- Use SVGs for generic dimensions (in case of stretching of images)
- Discuss about image Sprites for icons
- Discuss about progressive images (ex: Medium.com)
Instrumentation
- Measurement and tracking are key for a stable system
- Monitoring - code
- Error logging (for tracing)] - Using Google Analytics
- Debugging - Custom Tracking
- Logs/Track all events happened in the application - code
- Implement Analytics (GA) - this
- Sentry (to capture errors) - example - code
- Newrelic (to detect failures) - doc
Versioning of artifacts
- Artifacts tracking (ex: Confluence)
- Rollback & backup mechanisms
Performance Optimization Techniques
-
Webpack to optimized/compressed pages (Code splitting)
-
Using Web workers
- React and Web Workers
- Example - code
- Another example - code
- Using worker with Webpack 4 / Using worker with Webpack 5
-
Lighthouse / PageSpeed Insights - website having 100 score
-
Fast Loading (Initial load should be fast)
-
Smooth Operations (Loading indicators / Light/Smooth/Meaningful animations (to avoid jerks in transitions) / Splash screens) - (dialog with light animations)
- Example using react-spring - code
- Going jank free - Achieving 60 FPS smooth websites
-
Animation directions should be the same (dialog coming from bottom should close in bottom) - (smooth animation should be added in sidebars for better UX)
- Example using react-spring - code
- How To Implement Smooth Scrolling in React
-
Animation between data fetching(APIs request)
- Skeletal loaders
- Using blurhash
-
Discuss about Caching - ex: API, resource cache (Browser cache / Memory / CDN / Disk Cache)
-
Pagination vs Infinite Scroll
-
Meaningful animation
-
React specific issues
- Fixing Wasterd Rendering, Caching expensive operation results, Reducing bundle sizes, Lazy loading components - video code
- Checking Extra Renders - code
- Optimizing React Performance - 12 Tools and Tips
- Render Performance Optimization With React
Internationalization (i18n) / Localization (i10n)
- Localization - example live - code
- Numeric, date and time formats - date-fns library
- Singular & Plurals
- Use of currency
- Keyboard usage - example
- Symbols, icons and colors
- Text and graphics vary with different languages and religions, may be subject to misinterpretation or viewed as insensitive
- Varying legal requirements
Accessibility
- Alt attributes
- Aria-labels - example code
- Multi-device support, slow network speed
- Adaptive Loading - live - Code
- Color contrast, semantics tags - See this
Security
-
MITM
-
CSRF
-
Clickjacking
-
CORS
-
SSL Testing
- Deep analysis of the configuration of any SSL web server on the public Internet -Testing your SSL web server
-
Security Headers
- Analyzing HTTP response headers for sanity(https://securityheaders.com) - Example of good report
- badssl - https://badssl.com/
-
Other Tools
Quality assurance and control
-
Stable products are successful
-
Specify standards - Code level / Artifacts level / Asset level
- Code level - Git
- Artifacts level - Artifactory
- Asset level - Git/ Blob storage(S3 etc)/CDN
-
Git Hooks (pre commit hooks, husky)
-
- Example - code
-
- Example - code
-
Linters / Static Analyzers
-
Unit testing
- Mocking React Hooks - Example - blog - code
- React Hooks Testing Library - https://github.com/testing-library/react-hooks-testing-library
- React Testing Library example - code
- Code accompanying "Testing React with Jest and Testing Library" course on Udemy - Code
- Testing Library - thenewboston website - live - code
- React Jest example - code
- Async testing - code
-
Workflow testing (User level flows) (Tools - Cypress)
-
Integration testing
- e2e integration test using Mocha and Pupppeteer - code
-
Automation Suite
- Using webdriver IO that allows using sauce,browserstack etc - code
-
Cross browsers testing
-
Cross platform testing
- Cypress demo app - code
Governance
- Controlling the workflows and protecting the assets
- UX Design -> Developers -> Product Managers -> UX Designing -> QA
- Code level governance - like PRs approval (sets standard in your team)
- Artifacts/Assets level governance (before go live)
- like Product Manager approval, Stakeholders approvals
Experiment based release cycle
-
Experiment flag, which can help in the release cycle
Example : In a recent codebase I worked, we had a flag in the frontend codebase that was enabled/disabled based on the response received from API(in turn , API routes in node.js server were handled in 2 ways : 1) the server code read the values based on the server configuration(ENV values) for that particular deployment 2)actual backend that had its configuration as well) affecting the user experience and user journey.
NFR (Non Functional Requirement)
- Discuss about CI/CD (Docker, Pipeline)
- Alexander Kachkaev's personal website has a good pipeline setup - see code
Codebases + Guides Worth Mentioning Here
- Artsy.net - (https://github.com/artsy/force/)
- What to look for : completed production app, integrations/tooling
- thenewboston - (https://github.com/thenewboston-developers/Website)
- what to look for : complete production app, significant unit tests
- fakeflix - (https://github.com/Th3Wall/Fakeflix)
- what to look for : significant codebase that has more complete implementation than usual blogposts/articles
- CRWN Clothing - (https://github.com/Th3Wall/react-crwn-cothing-ecom)
- algorithm-visualizer - (https://github.com/algorithm-visualizer/algorithm-visualizer)
- What to look for - abstraction for components
- spotify-clone-client - (https://github.com/JL978/spotify-clone-client)
- What to look for : simple app with clean modern Hooks implementation
- The Front-End Checklist - (https://github.com/thedaviddias/Front-End-Checklist)
- What to look for : missing points from this document spoken at more detailed length
- Engineering Best Practices - (https://10up.github.io/Engineering-Best-Practices/)
- What to look for - many sections here serve as a good reference on their own
- Zero to production web apps - code
- What to look for - independent end to end simple setup that can be used as a base template
- Bulletproof react -code
- What to look for - readymade opinionated guide
- For adding Typescript to web app
- React Redux Typescript Guide - (https://github.com/piotrwitek/react-redux-typescript-guide)
- Typescript cheatsheet - (https://github.com/typescript-cheatsheets/react)
Boilerplate Code
- Setup with Node.js web application server acting as a Backend for Frontend
- Next.js setup
- React, Redux, Redux-saga,Styled components boilerplate
- SSR boilerplate
- Boilerplate (seed) project for creating web apps with React.js, GraphQL.js and Relay
- Boilerplate and tooling for web application development based on React (ReactJS), Redux, Babel, Webpack, CSS Modules, PostCSS, Browsersync, React Hot Loader and optimized for CDN hosting in Firebase
- Universal React Starter
- New York Times kyt based starterkit
- Create React App - Simple Redux Typescript Boilerplate
- Create React App - react redux redux-saga ant-design tailwind-css boilerplate
Setting up Development Environment
- Git and SSH Keys
- Code to deploy an EC2 instance for development purposes.
- HTTPS on local dev env
- Using Prettier and husky to make your commits safe
- git cheatsheet
License
This repository is MIT licensed. Read more