Best Practices for Component Design and Encapsulation in React
The article outlines React component design best practices by distinguishing generic UI components from business‑specific ones, separating UI and domain state, extracting reusable base components, applying patterns such as state lifting, context, memoization, and type‑safe props, and providing a checklist for clean encapsulation.
Good component design and encapsulation are the foundation of front‑end development.
The article explains how to distinguish basic (generic) components from business‑specific components, using Ant Design as an example of a basic component library.
Key concepts include separating generic features (UI‑level) from custom features (business logic), and organizing state into UI state and domain (business) state, inspired by Domain‑Driven Design.
Common patterns such as content lifting, context, third‑party state management, and memoization are discussed.
const SubmitButton = (props) => {
return
{props.buttonText}
}
const SubmitButton = (props) => {
return
{props.isAdd ? '新增' : '编辑'}
}To improve reusability, generic features are extracted into a base component:
const BaseButton = (props) => {
const { buttonText } = props;
return
{buttonText}
}
const SubmitButton = (props) => {
const { buttonText, isAdd } = props;
return
}Node rendering can be abstracted with a map and a base node wrapper:
const NODE_MAP = {
start: StartNode,
llm: LLMNode,
end: EndNode
}
const CustomNode = (props) => {
const { type } = props;
const RenderNode = NODE_MAP[type];
return
}Memoization with React.memo helps avoid unnecessary renders when props are unchanged:
const Parent = (props) => {
return
}
const Child = (props) =>
{props.name}
const MemoChild = memo((props) =>
{props.name}
)State lifting example demonstrates moving state updates to the parent to give child components only the needed handlers:
const Parent = () => {
const [state, setState] = useState({ name: 'han', sex: 'man' })
const handleChangeName = (name) => setState({ ...state, name })
return (
name: {state.name}
sex: {state.sex}
)
}The article concludes with a checklist for component design: determine generic vs custom level, separate UI and business features, apply composition and state‑placement techniques, and consider TypeScript typings, props definitions, and styling.
DaTaobao Tech
Official account of DaTaobao Technology
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.