paint-brush
Newbie React Developer? Watch Out for These 15 Common Mistakes by@jonystorm
653 reads
653 reads

Newbie React Developer? Watch Out for These 15 Common Mistakes

by Md. JonyAugust 27th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

1. Not Starting a Component’s Name with a Capital Letter 2. Not Creating Enough Components 3. Not Understanding the Virtual DOM 4. Not Understanding the Component Lifecycle 5. Not Using the “key” Attribute in Listing Component 6. Not Using the Optional Chaining Option 7. Modifying the State Directly 8. Using Duplicate State 9. Forgetting that setState() Is an Async Function 10. Underutilizing Redux or Using Redux so much 11. Not Using Multiple useEffect() 12. Passing Props Down as Strings Instead of Numbers 13. Using Anchor Tag for Navigation rather than Using the Link Component 14. Not Understanding Event Handling 15. Not Using the React Developers Tools and ESLint Plugin
featured image - Newbie React Developer? Watch Out for These 15 Common Mistakes
Md. Jony HackerNoon profile picture


Hi there!


React is arguably the most popular JavaScript library for building user interfaces by creating reusable and composable components and managing the state of the application consistently and efficiently.


However, as with any new technology, there are some common mistakes that every newbie React developer tends to make.


In this article, l am going to point out some of the most common mistakes that every newbie React developer makes along with some code snippets to help you understand and avoid them.



1. Not Starting a Component’s Name with a Capital Letter

As a newbie React developer, the very first common mistake that you might make is not starting the name of a component with a capital letter. React treats components with a lowercase name as built-in HTML elements, while components with a capitalized name are treated as custom components.


For an example:

class demoComponent extends React.Component {} // wrong
class DemoComponent extends React.Component {} // correct
function demoComponent({ props }) {} // wrong
function DemoComponent({ props }) {} // correct
const demoComponent = ({ props }) => {} // wrong
const DemoComponent = ({ props }) => {} // correct


Not following this convention might lead to unexpected behavior and bugs, as well as make it difficult for other developers to understand the codebase. Always make sure to start the name of a component with a capital letter to indicate that it's a custom component and to follow the React conventions.



2. Not Creating Enough Components

The second most common mistake that a newbie often makes is not creating enough components. In React, it's important to create reusable and composable components to make the codebase more organized and easier to understand.


Creating one big component can lead to a codebase that's difficult to maintain and understand, as well as make it difficult to ensure that the data is consistent across the application. To avoid this mistake, you should always create reusable and composable components, and break down the application into smaller and manageable parts.


For an example consider the following application:

LamaSocial Frontend


If you want to build the above application then you need to make reusable components like navbar, sidebar, rightbar, post, feed, etc. By combining small reusable components you will be able to make complex maintainable components.



3. Not Understanding the Virtual DOM

The Virtual DOM is actually an abstraction of the actual DOM (Document Object Model) in React. It is a lightweight JavaScript object that represents the structure of a UI component. Understanding the Virtual DOM is crucial for writing efficient and performant React code. Most of the time, a newbie doesn't understand how the virtual DOM works. As a newbie, you may also write code that directly manipulates the DOM, which can lead to poor performance and unexpected behavior. To avoid this mistake, you must understand the basics of the Virtual DOM, such as how it works, how it compares to the actual DOM, and how React updates the Virtual DOM. Additionally, it is important to understand that React components are just functions that return Virtual DOM elements.


4. Not Understanding the Component Lifecycle

The component lifecycle is another most important concept in React, it determines the order in which the components are created, updated, and destroyed. When you don’t understand the component lifecycle, you might end up getting unexpected behavior and bugs. You should fully understand the component lifecycle, and how to use it to create, update, and destroy components in the correct order so that you don’t end up getting unexpected bugs and errors.


5. Not Using the “key” Attribute in Listing Component

When working with lists in React, it's important to use the "key" attribute to uniquely identify each item. Not using the "key" attribute might lead to unexpected behavior and bugs, as well as poor performance.


Let’s examine the examples below:

const studentList = ['John', 'Jane', 'Kevin', 'David', 'Ashley'];
const StudentListComponent1 = () => {
  return(
    <ul>
      studentList.map((student, index) => {
        return <li> {student} </li>; // wrong
      })
    </ul>
  )
}

const StudentListComponent2 = () => {
  return(
    <ul>
      studentList.map((student, index) => {
        return <li key={index}> {student} </li> // correct
      })
    </ul>
  )
}

React will also give you a warning saying "A key should be provided for list items" if you don’t use the "key" attribute in a list. So always keep it in mind.


6. Not Using the Optional Chaining Option

The optional chaining operator is a new feature in JavaScript that allows developers to access the properties of an object without worrying about whether the object is undefined or null. Using this feature you can save a lot of your debugging time when building React applications. It will also make your code much simpler to read and understand.

let [users, setUsers] = useState({})
console.log(users.name) // undefined
console.log(user.name.length) // will give an error
console.log(user.name?.length) // undefined

You should make sure that you’re using the optional chaining operator when accessing the properties of an object, and ensure that your code is safe and robust.



7. Modifying the State Directly

In React, the state should never be modified directly. Instead, the setState() function should be used to update the state, this will ensure that the component re-renders and the virtual DOM is updated correctly.

class Counter extends Component {
    constructor(props) {
        super(props)
        this.state = {
            counter: 0,
        }
    }
   increment() {
        this.state.counter = this.state.counter + this.props.increment // this is wrong
        this.setState((prevState, props) => ({
            counter: prevState.counter + props.increment // this is the correct way
        })
    }
}

Modifying the state directly will lead to unexpected behavior and bugs, as well as poor performance. You should always make sure to always use setState() to update the state, and never modify the state directly.


8. Using Duplicate State

Another common mistake that new React developers make is using duplicate states. This can lead to confusion and bugs, as well as make it difficult to ensure that the data is consistent across the application. To avoid this mistake, you have to make sure to use a centralized state management solution such as Redux, and avoid duplicating state in multiple components.


9. Forgetting that setState() Is an Async Function

setState() is an async function in react, it does not update the state immediately. This might lead to unexpected behavior and bugs, as well as make it difficult to ensure that the data is consistent across the application. You have to make sure that you understand, setState() is an async function and you can pass a callback function to setState() which will be called once the state has been updated so that you don’t end up getting unexpected behavior.


10. Underutilizing Redux or Using Redux so much

Redux is a popular state management library for React applications, it can help to keep the state of the application consistent and organized. However, many new React developers tend to either underutilize or overuse Redux. Underutilizing Redux will lead to a difficult-to-manage state while overusing Redux can make the codebase overly complex. You should make sure you understand when and how to use Redux in your application. You should use it only when it's necessary. It's important to weigh the benefits and drawbacks of using Redux and consider alternative solutions such as the useContext() and useReducer() hooks before adding them to your application.


11. Not Using Multiple useEffect()

useEffect() is a hook in React that allows developers to synchronize a component with an external system. Not using multiple useEffect() can lead to unexpected behavior and bugs, as well as make it difficult to ensure that the data is consistent across the application. To avoid this mistake, always make sure to use multiple useEffect() to synchronize a component with an external system, and ensure that the component re-renders correctly when the state changes.


12. Passing Props Down as Strings Instead of Numbers

Many new React developers tend to pass props as strings instead of numbers or booleans, this can lead to unexpected behavior and bugs in your application.

const User = ({ name, age }) => <p>{ name } is { age }</p>
<User name="Jack" age="29" /> // this is wrong
<User name="Jack" age={29} /> // this is correct

Always make sure to pass props down as the correct data type, not as strings to avoid this mistake.


13. Using Anchor Tag for Navigation rather than Using the Link Component

In React, it is not recommended to use anchor tags for navigation, instead, use the Link component provided by React Router. Using anchor tags for navigation might lead to unexpected behavior and bugs in your application.

const Navigation = () => {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <a href="/about">About</a> // you should not use anchor tag
          </li>
          <li>
            <Link to="/about">About</Link> // rather use Link Component
          </li>
        </ul>
      </nav>
    </div>
  );
};

You should always use the Link component provided by React Router for navigation wherever necessary to avoid this mistake.


14. Not Understanding Event Handling

Another common mistake that new React developers make is not understanding event handling. Event handling in React is similar to event handling in JavaScript, but it is done in a slightly different way. Not understanding event handling can lead to unexpected behavior, such as an event not firing or a component not updating when it should. You must understand the basics of event handling in React, such as how to bind events to components and how to pass event handlers as props to avoid this mistake. Additionally, it is important to understand that React events are synthetic events and not like native DOM events.


15. Not Using the React Developers Tools and ESLint Plugin

At last, new React developers do not know or use the React Developer Tools and the ESLint plugin. The React Developer Tools is a browser extension that allows developers to inspect and debug their React application. On the other hand, ESLint is a tool that checks the code for errors and helps to maintain a consistent code style. Using these two tools is very important for ensuring that the application is working as expected and to catch any bugs early on in the development process. Not using these tools might lead to bugs and unexpected behavior in the application. You should always make sure to use the React Developer Tools and the ESLint plugin as part of your development process.


Conclusion

As a new React developer, it's important to be aware of the most common mistakes and to take steps to avoid them. By understanding the importance of components, the virtual DOM, the component lifecycle, state management, and other important concepts, you can create robust and high-performing applications with React. Additionally, by using the tools and best practices discussed in this article, you can ensure that your code is clean, maintainable, and free of bugs. Remember that practice and patience are the keys to success, don't be afraid to experiment and make mistakes, as they are a part of the learning process!