amit kumar
4y ago
Welcome to my Social Blog
Writing great code doesn't have to be complex. These simple tips will help you build React apps that are very easy to test, update and are super flexible.
Unfortunately we often build apps without thinking about how it will evolve to future changes.
How these techniques will be a life-saver
Here are some common scenarios in which these small techniques will prove a life-saver:
Easy to test.
Adapt to future updates.
Separation of business logic.
Predictable data flow.
Writing future-proof components
Always remember these thumb rules when writing components:
UI components should always be unaware of the network requests, business logic, or app state.
Components should be written like a pure function. It simply means that it should always render same data when provided same props.
For a detailed guide to writing great components. Check out this guide.
Making evolution easy with HOCs
React Higher Order Component (HOC) is a component that takes a component and returns a component.
Always remember these thumb rules when writing HOC:
Always prefer to create those HOCs which don't create any props. If your HOC need to create props, always make sure it is not creating more than one.
Use HOC when that behavior is used either by multiple components or all components in the app.
Make sure the component can work without HOC. Components should not create a dependency with HOC.
A component can be directly wrapped in HOC without having to add additional logic to it.
Architect your app for clean code
Never mix view render concerns, data processing and data fetching in a single place. Mixing everything will lead to a spaghetti architecture and will become painful in future.
Always make your component as dumb as possible. A component should always render same thing given the same state.
Flux architecture allows you to create a predictable data flow for your app. In this architecture event listeners listen for things like: user input handlers, network request handlers. When event listeners get them, it dispatches actions to the store. State is only be updated when an action is dispatched.
Use flux architecture based libraries like Reflux, Redux, etc. in below scenarios:
Component uses network request or device API.
Has common application states.
Component needs business logic or data manipulation logic that is shared with other parts of app.
Using flux architecture will not only allow you to build highly flexible UI components, it will also allow you to separate things like business logic from your component. It will allow you to easy migration to different data fetching techniques. The predictable unidirectional data flow will make your app easy to debug and test.