React is becoming a full-stack framework with React Server Components and Server Actions. While React Server Components (RSC) allow us to read data in the UI from the database, Server Actions enable us to write data back to the database. Certainly UI and database will be close and simple in a small application, but in a larger application, there will always be the complexity of unintentionally intertwining vertical features.
Here I want to discuss how to create a feature-based architecture in React that allows large scale applications to be built and maintained. In a feature-based architecture, each feature is decoupled from the others as much as possible. This way we can keep the components and their data fetching functions focused on their domain.
Feature-Based React Components
In a typical application, we will have a database with multiple tables that are related to each other. For example, a blog application might have a users table, a posts table, and a comments table. The posts table might have a foreign key to the users table, and the comments table might have foreign keys to both the users and posts tables.
Let's take the posts and comments relationship without taking the user table into consideration, for the sake of simplicity, and see how it will influence the architecture:
model Post {
id String @id @default(cuid())
title String
content String
comments Comment[]
}
model Comment {
id String @id @default(cuid())
content String
post Post @relation(fields: [postId], references: [id])
postId Int
}
In a React component structure, we might have a Post component that renders a post and its comments. The Post component, as a Server Component, might look something like this, where we fetch the post and its comments from the database:
import { getPost } from '@/features/post/queries/get-post';
const Post = async ({ postId }: { postId: string }) => {
const post = await getPost(postId);
return (
<>{post.title}>
{post.content}
-
{post.comments.map((comment) => (
- {comment.content} ))}
);
}
However, in order to keep our components focused, we might want to split the Post component into two components: a Post component that renders the post itself, and a Comments component that renders the comments. We focus each component on a single feature and therefore can also enforce a clean feature-based architecture:
import { Comments } from '@/features/comment/components/comments';
import { getPost } from '@/features/post/queries/get-post';
const Post = async ({ postId }: { postId: string }) => {
const post = await getPost(postId);
return (
<>{post.title}>
<>{post.content}>
comments{post.comments}
/>
);
}
Splitting up components into smaller components is a best practice which comes with many advantages. Here we want to focus on the feature architecture and how it simplifies each file in its own feature folder by decoupling features as much as possible
Source
The above is the detailed content of Feature-Based React Components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
