-
Notifications
You must be signed in to change notification settings - Fork 7
REACT Best Practices
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.
Props provide configuration values for your component.
- Always use camelCase for prop names. Props can also be seen as attributes, and the convention set by React is to use camelCase for JSX attributes. Which makes it a good practice to always use camelCase for props.
- Omit the value of the prop when it is explicitly true.Even if we don’t assign true value to a prop, It’s considered as a true value, so there’s no need to assign ‘true’ as a value to the prop.
- Avoid using an array index as key prop, instead use an unique ID: DO NOT USE THE INDEX OF AN ITEM AS ITS KEY WHEN RENDERING A LIST. Don't do this:
The key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something from the middle? If the key is the same as before, React assumes that the DOM element represents the same set of components as before. Which is not the case, this is why it is advised to USE A UNIQUE ID. Each item should have a permanent and unique property. Ideally, a unique id should be assigned to each item at the time of creation. So it’s written out something like this:
- Always define explicit defaultProps for all non-required props. Providing defaultProps means the reader of your code doesn’t have to assume things, because they’ll know the default value for the prop just by looking at defaultProps while rendering components
1. Use bindActionCreators for dispatching actions Redux’s event dispatching system is the heart of its state management functionality. However, it can be tedious to pass down the dispatch function as a prop to every component that needs to dispatch an action.
Avoid this.
Avoid this.
instead do this
In the above code filterTalentPoolDataBySkills
in bindActionCreators
is available as this.props.filterTalentPoolDataBySkills
to dispatch your action. It will make it easier to maintain the code for long run.
Manage the application state using redux store when it is in global state. Avoid using setState in your component when you are using state management libraries like redux. Use component state when it makes sense ie. A Button component that shows a tooltip when hovered would not use Redux.
Avoid Doing this.
Instead do this
Here we used the redux store to get state and render it in the view directly. There is no need of using setState and component lifecycle hooks again. Redux is there to do the state management job for you.
There are two ways of binding the custom component’s this
scope.
- Binding them in constructor.(Do this)
With this way only one extra function is created at the time of component creation, and that function is used even when render is executed again.
- Binding at the time of passing as prop value (Avoid this).
.bind()
method creates a new function each time it is run, this method would lead to a new function being created every time when the render function executes. This has performance implications. In small applications we cannot notice them, however in large applications we can notice them.
Solution:
- It's better to bind your custom functions in constructor.
- There is a Babel plugin called Class properties transform . You can write auto-bound function using the fat-arrow syntax.
If we see the above code there are no functions to bind.
For better code refactoring move all your functions which do filtering , parsing and other data transformation logics into seperate file and import them to use those functions inside your connect method of react-redux as shown.
By doing this, it will be easy to add flow types for your functions.
Writing cleaner code will make it easier understand and maintain the code. ES6 features will give us much cleaner way of writing code in React.
- Use Destructuring & spread attributes:
Avoid this.
Instead do this.
- Use Arrow functions
Avoid this:
As the javascript project grows without typing, the more difficult refactoring will become. The larger the project the higher the risk when refactoring. Using type checking may not completely eliminate risk but it will greatly reduce it.
Benefits in using flow:
- On time detection of bugs or errors.
- Communicates the purpose of the function.
- It Scales Down Complex Error Handling.
- Wipes Out Runtime Type Errors.
Fetch API and axios are the most preferable ways of making http requests. Between those two there are some advantages of using axios library.
They are:
- It allows performing transforms on data before request is made or after response is received.
- It allows you to alter the request or response entirely (headers as well). also perform async operations before * request is made or before Promise settles.
- Built-in XSRF protection.
The basic idea of styled-components is to enforce best practices by removing the mapping between styles and components. This way, you can collocate your components with their corresponding styles , resulting in localised class names that do not pollute the global css namespace. When using styled-components, do not forget to plugin to support syntax highlighting in strings or maybe create a new one.
Example:
Folder structure is very important when there is a large project at hand, because if the files are not well placed or segregated, developers often get confused and waste precious time looking for files.
--sugest folder structure here with clear definition of the contents of each folder--