React

10 Common mistakes in ReactJS for beginners.

10 Common mistakes in react for beginners.

In the process of developing with React, some mistakes can be made, which can cause issues with the code. In this article, we will outline 10 common mistakes in React development that developers should avoid.

1. Not using the key when rendering a list

When rendering a list in React, it is important to use a key attribute for each item to help React identify which elements have changed, such as those that have been added or removed. Without a unique key, the performance of your app may degrade. Therefore, it is important to set a unique value for each element in the array.

// problem
const people = [{id: 1, name: 'bob'}, {id: 2, name: 'John'}];
const listItems = numbers.map((person) => <li>{person.name}</li>);

// solution
const people = [{id: 1, name: 'bob'}, {id: 2, name: 'John'}];
const listItems = numbers.map(({id, name}) => <li key={id}>{name}</li>);

2. Modifying the state value directly by assignment

In React, state should not be directly assigned and modified. This will cause issues that are difficult to fix. Instead, class components can be modified with the setState() method, while function components can be modified with useState().

// problem
const [age, setAge] = useState(30)
updateState = () => {
  age = 30;
};

// solution
setAge(30)

3. Binding the state value directly to the value property of the input

When binding the value of state as a parameter to the value property of the input tag, you may find that the content of the input box will not change. This is because the state in the functional component can only be modified by the set method returned by useState(). To modify the state, bind an onChange event to the input and call the set method.

// problem
export default function App() {
  const [email, setEmail] = useState('');
  return <input type="text" value={email} />;
}

// solution
export default function App() {
  const [email, setEmail] = useState('');
  const onInputChange = (val) => setEmail(val.value);
  return <input type="email" value={email} onChange={onInputChange} />;
}

4. Creating an infinite loop when using useState() + useEffect()

When using the useState() and useEffect() hooks, be careful not to create an infinite loop. This can happen when you set the state in the useEffect() hook without specifying a condition for when the hook should be called.

// problem
export default function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    // this will lead to App rerendering
    // what means this useEffect should be called again
    setCount(count + 1);
  });
  return <div className="App">{count}</div>;
}

// solution
export default function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    setCount(count + 1);
    // firing only once
  }, []); // <--
  return <div className="App">{count}</div>;
}

5. Forgetting to clean up side effects in useEffect()

When using the useEffect() hook to manage side effects, it is important to clean up after yourself. Failing to do so can lead to memory leaks and other issues. To clean up, return a function that undoes the side effect.

// problem
useEffect(() => {
  // on every time conponent rerender
  // window will add one more 'resize' event
	window.addEventListener('resize', handleResize);
}, []);

// solution
useEffect(() => {
	window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);

6. Incorrect use of boolean operators

Be careful when using boolean operators in your code. For example, using the && operator instead of the || operator when setting a default value can lead to unexpected behavior.

// problem
const count = 0;
const Component = () => count && <h1>Brightside</h1>;

// solution
const count = 0;
const Component = () => count > 0 && <h1>Brightside</h1>;

// better solution
const count = 0;
const isNameVisible = count > 0;
const Component = () => isNameVisible && <h1>Brightside</h1>;

7. Undefined component parameter type

It is important to define the type of component parameters. This helps catch errors before runtime and improves the overall code quality.

// problem
const UserInfo = (props) => {
  return (
    <div>
      {props.name} : {props.age}
    </div>
  );
};

// solution
// FunctionComponent
interface AppProps {
  value?: string;
}
const App: React.FC<AppProps> = ({ value = "", children }) => {
  //...
};

8. Passing strings as values to components

When passing values to components, it is important to ensure that the data type matches the expected type. Passing strings as values can lead to unexpected behavior and errors.

// problem
<Component count="55"></Component>

// solution
<Component count={55}></Component>

9. Not using a capital letter at the beginning of a component name

When defining a component in React, it is important to start the component name with a capital letter. This is because React treats lowercase component names as DOM tags.

// problem
<userComponent user={}></userComponent>

// solution
<UserComponent user={}></UserComponent>

10. Using inline functions

When binding an event to an element, be careful to use the correct syntax. For example, using an arrow function to bind the event can cause performance issues.

// problem
<Component handler={() => console.log('test!')} />

// solution
const handlerFunc = () => {
  console.log('test!');
}

<Component handler={handlerFunc}/>

In conclusion, these are 10 common mistakes in React development that you should avoid. By keeping these tips in mind, you can develop with React more efficiently and effectively.

A blog for self-taught engineers

Сommunity is filled with like-minded individuals who are passionate about learning and growing as engineers.