React Thinking: How Not to Turn Code into " Spaghetti " ?
Transitioning from regular HTML to React is not just about changing tag names. It's a philosophy shift. In HTML, you wrote one long " sheet " of code. In React, you become an architect who builds a structure from ready-made blocks. This process of dividing the whole into parts is called Decomposition.
1. Analogy: Building a Cathedral
You cannot 3D print a cathedral all at once.
- You have bricks (smallest elements: buttons, icons).
- You have windows and doors (assembled from bricks and frames).
- You have halls (consisting of windows, walls, and doors).
- The Cathedral is just the final component that knows where to place each hall.
In React, it's exactly the same. We go from small to large.
2. Single Responsibility Principle (SRP)
This is the main rule of a cool developer. Your component should do one thing, but do it perfectly.
- Bad: A component
UserInfoAndWeatherAndNews. If the weather display breaks — the entire user profile might crash. - Good: Three separate components:
UserAvatar,WeatherData,NewsList.
If a component does too much — it's hard to read, impossible to test, and unrealistic to reuse.
3. Checklist: When to Create a New Component?
You don't need to atomize code just for the sake of it. Extract code into a separate file if:
- Repetition: You see the same piece of markup (e.g., a product card) in five different places.
- ** " Fat " file:** Your component has exceeded 100 lines. Your eyes start getting tired while scrolling to the right place.
- Complex logic: If one component solves five different tasks at once (validation, API request, animation, price calculation), it's time to split them.
- Meaningful name: If you can isolate a piece of code and give it a clear name (e.g.,
SubscribeForm), then that piece deserves to be a component.
4. Dumb and Smart Components (Pattern)
- ** " Dumb " components:** These are like soldiers. They don't ask questions. They were given data (via props) — they display it. They don't know about databases or APIs. They're easy to move from project to project.
- ** " Smart " components (Containers):** These are generals. They know where to get data, how to process it, and how to pass it to " soldiers. " They connect logic with visuals.
Once you master decomposition, you'll stop fearing complex interfaces. Any giant page is just 20-30 small, understandable functions.