REACT Best Practices Components - AndelaOSP/Andela-Socials GitHub Wiki
Components
A React component is basically any part of your UI. When designing components, always divide the UI into logical chunks. Each of these UI chunks are potential components.
1. Break The UI Into A Component Hierarchy:
Typically a single view of a user interface (e.g., the tree or trunk) is divided into logical chunks (e.g., branches). The tree becomes the starting component (e.g., a layout component) and then each chunk in the UI will become a sub-component that can be further divided into sub-components (i.e., sub-branches). This not only keeps our UI organized but it also allows data and state changes to logically flow from the tree to the branches, and then the sub branches.
2. Choosing the right Components:
Functional Component: Use a functional component if your component doesn’t do much more than rendering props. One way to think of these are as pure functions, because they will always render and behave the same, given the same props. Also, they don’t care about life-cycle methods and/as they are are Stateless Components.
example:
Class Based component: If a component needs internal state and component life-cycle methods then go for a class based component. example:
3. Differentiate Presentational Components and Container Components. When we are architecting a react application with redux, we should split our components into presentational and container components. Presentational components are components that render HTML. All our presentational components are stateless components, so are written as functional stateless components unless they need state and lifecycle hooks. Presentational components will not interact with redux store for state. They receive data via props and render it. Container components are for getting data from redux store and providing the data to the presentational components. They tend to be stateful.
Presentational Component should be stateless functional component as shown:
Container Component should be stateful functional component until unless you are forced to use React component lifecycle methods.
Points to be noted:
- We can see improved performance when using stateless functional components.These components avoid unnecessary checks and memory allocations and are therefore more performant.
- It will be easy to test a component , if you write the component as simple as possible by splitting presentational components and container components.