React developers need to know how to use it properly when writing code for their projects. They should also be able to learn the best practices of React development in order to make sure that they are not wasting time on things that aren’t adding value to the project.
But how to do it?
We are trying to present a quick guide on React best practices that will show you the right way of working with React in order to make React app development easier and more effective.
#1 Keep Components Size To The Minimum
Restricting the size of components is an effective practice to make your code cleaner and easy to maintain. So you must be wondering, what would be the idle size of a component?
We recommend you not to create components that have more than ten lines of code. You can always split components into multiple smaller components and also re-use them wherever needed. The goal is to keep the components easier to maintain, update and debug.
Let’s look at the following example:Before
///
// file: index.jsx
// file: index.jsx
import React from ‘react’
const books = [
{
category: ‘Literature’,
price: ‘$20.00’,
name: ‘ Anna Karenina’,
author: ‘Leo Tolstoy’
},
{
category: ‘Literature’,
price: ‘$25.00’,
name: ‘Hamlet’,
author: ‘ William Shakespeare’
},
{
category: ‘Modern literature’,
price: ‘$15.95’,
name: ‘In Search of Lost Time’,
author: ‘Marcel Proust’
},
{
category: ‘Magic realism’,
price: ‘$21.00’,
name: ‘One Hundred Years of Solitude’,
author: ‘Gabriel Garcia Marquez’
},
{
category: ‘Novel’,
price: ‘$29.99’,
name: ‘The Great Gatsby’,
author: ‘F. Scott Fitzgerald’
‘},
{
category: ‘Fiction’,
price: ‘$4.81’,
name: ‘The Catcher in the Rye’,
author: ‘J. D. Salinger’
‘}
]
class Bookshelf extends React.Component {
render() {
const tableRows = []
this.props.books.forEach((book) => {
tableRows.push(
<tr>
<td>{book.name}</td>
<td>{book.author}</td>
<td>{book.price}</td>
<td>{book.category}</td>
</tr>
)
})
return (
<div>
<form>
<input type=”text” placeholder=”Search…” />
<button>Search</button>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Price</th>
<th>Category</th>
</tr>
</thead>
<tbody>{tableRows}</tbody>
</table>
</div>
)
}
}
// Render Bookshelf component
ReactDOM.render(<Bookshelfbooks={booksData}/>,document.getElementById(‘container’))
After
///
// file: index.jsx
import React from ‘react’
const books = [
{
category: ‘Literature’,
price: ‘$20.00’,
name: ‘ Anna Karenina’,
author: ‘Leo Tolstoy’
},
{
category: ‘Literature’,
price: ‘$25.00’,
name: ‘Hamlet’,
author: ‘ William Shakespeare’
},
{
category: ‘Modern literature’,
price: ‘$15.95’,
name: ‘In Search of Lost Time’,
author: ‘Marcel Proust’
},
{
category: ‘Magic realism’,
price: ‘$21.00’,
name: ‘One Hundred Years of Solitude’,
author: ‘Gabriel Garcia Marquez’
},
{
category: ‘Novel’,
price: ‘$29.99’,
name: ‘The Great Gatsby’,
author: ‘F. Scott Fitzgerald’
‘},
{
category: ‘Fiction’,
price: ‘$4.81’,
name: ‘The Catcher in the Rye’,
author: ‘J. D. Salinger’
‘}
]
export default booksData
///
// file: components/books-table.jsx
import React from ‘react’
class BooksTable extends React.Component {
render() {
const tableRows = []
this.props.books.forEach((book) => {
tableRows.push(
<tr>
<td>{book.name}</td>
<td>{book.author}</td>
<td>{book.price}</td>
<td>{book.category}</td>
</tr>
)
})
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Price</th>
<th>Category</th>
</tr>
</thead>
<tbody>{tableRows}</tbody>
</table>
)
}
}
export default BooksTable
///
// file: components/search-bar.jsx
import React from ‘react’
class SearchBar extends React.Component {
render() {
return (
<form>
<input type=”text” placeholder=”Search…” />
<button>Search</button>
</form>
)
}
}
export default SearchBar
///
// file: components/bookshelf.jsx
import React from ‘react’
// Import components
import BooksTable from ‘./components/books-table’
import SearchBar from ‘./components/search-bar’
class Bookshelf extends React.Component {
render() {
return (
<div>
<SearchBar />
<BooksTable books={this.props.books} />
</div>
)
}
}
export default Bookshelf
///
// file: index.jsx
import React from ‘react’
// Import components
import Bookshelf from ‘./components/bookshelf
// Import data
import booksData from ‘./books-data’
// Render Bookshelf component
ReactDOM.render(<Bookshelf books={booksData} />, document.getElementById(‘container’))
#2 Grouping According To Features
The public folder and src directory are the two base directories in your React app. In the src directory, you will have basic files such as App.js and index.js in the root of the folder. And you will also have nested directories for every feature in your React app.
Your application may have other directories or nested into components, testing and styling as well, so according to that, file organisation may vary.
src/
App.js
App.css
App.test.js
index.js
global/ ⇐ items that are in common with entire application
AppContext.js
ThemeContext.js
UserContext.js
Button.js
cards/
index.js
Cards.css
Cards.js
Card.css
Card.js
Card.test.js
detailed-product/
DetailedProduct.css
DetailedProduct.js
DetailedProduct.test.js
checkout/
ReviewOrder.css
ReviewOrder.js
ReviewOrder.test.js
ShoppingCart.css
ShoppingCart.js
ShoppingCart.test.js
user/
index.js
User.css
User.js
User.test.js
#3 Grouping According To File Type
src is the folder where you should keep every file that is supposed to be rendered on the screen. As we said earlier, we will keep the App.js and index.js files in the root and other directories representing parts of the application, which are as follows:
- Components
- Context
- CSS
- Hooks
- Tests
src/
App.js
index.js
components/
App.css
Card.js
Cards.js
ConfirmationPage.js
DetailedProduct.js
Footer.js
Navbar.js
ReviewOrder.js
Settings.js
ShoppingCart.js
User.js
context/
AppContext.js
ThemeContext.js
UserContext.js
css/
Card.css
Cards.css
ConfirmationPage.css
DetailedProduct.css
Footer.css
Navbar.css
ReviewOrder.css
Settings.css
ShoppingCart.css
User.css
hooks/
useAuth.js
useAxios.js
…other custom hooks
tests/
App.test.js
Card.test.js
Cards.test.js
ConfirmationPage.test.js
DetailedProduct.test.js
Footer.test.js
Navbar.test.js
ReviewOrder.test.js
Settings.test.js
ShoppingCart.test.js
User.test.js
This is the basic structure of your application, and you should implement the same in your React app. However, the structure of the app may slightly vary depending on the kind of file your project has.
#4 Proper Handling Of Props
The process of passing props from parent component to child (several generations) is known as props drilling. This process should be avoided because it’s prone to error, and it is difficult to maintain the proper flow of data. In case it is necessary to give children access to the state, then you create a design pattern for global state management with Redux or Context API.
#5 Minimum Usage Of Stateful Components
Before the introduction of React hooks, when a developer wanted to use a lifecycle method, it was mandatory to use stateful components. In the React 16.8.0 version, Hooks were introduced, after which React developers are no longer restricted from using stateful components in order to use state.
Why should you avoid stateful components?
Stateless or functional components are the components that are crisp, less code to be processed. Following is the example of a button that is defined in stateful and stateless components to see which is more suitable for your application.
// Button – stateful component
class Button extends React.Component {
handleClick = () => {
// Do something
}
render() {
return(
<button type=”button” onClick={this.handleClick}>Click me</button>
)
}
}
// Button – functional component
const Button = () => {
const handleClick = () => {
// Do something
}
return(
<button type=”button”>Click me</button>
)
}
#6 Do Not Repeat Your Code
Just like any other technology, React best practices also includes keeping your code short and sweet. One of the ways to achieve this is to avoid duplicating the code.
Inspect your code for similar patterns; if you find any similarities, then consider deleting that code, or you can also rewrite the code.
Over To You
That’s all for essential React best practices that every developer should follow while developing React applications. We can assure you that these React best practices will help you to be more effective as it simplifies the development process. You can also hire React developers from EnProwess.
EnProwess is an offshore web development company established with a vision to enable businesses to take advantage of tech and expand their customer base. For more information, visit our website.