What is wrong with my code?


import React from 'react';

let users = [
  {
    id: 1,
    name: 'John',
    email: ''
  },
  {
    id: 2,
    name: 'Jane',
    email: ''
  },
  {
    id: 3,
    name: 'Josh',
    email: ''
  },
];

function Test() {
  const handleOnClick = () => {
    users.push({
      id: 4,
      name: 'New User',
      email: ''
    });
    console.log('Clicked');
  };

  return (
    <div>
      <h1>Test</h1>
      <button onClick={handleOnClick}>Click Me</button>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name}
          </li>
        ))}
      </ul>
    </div>
  )
}

export default Test;

Answer


The provided code is a React component that displays a list of users and a button to add a new user to the list. When the button is clicked, the new user is pushed into the 'users' array, and a message "Clicked" is logged to the console.

Here are a few observations about this code:

1. **Mutating State Directly**: The code is directly mutating the 'users' array by pushing a new user. In React, it's a bad practice to directly mutate the state (or any prop). Instead, React components should be based on the principle of immutability.

2. **UI Doesn't Re-render**: Even though you are adding a new user to the 'users' array, the UI won't re-render to show the new user. React components re-render when 'state' or 'props' change. In this case, you're not using state, so the component won't know when to re-render.

Here's a revised version of the code that uses the 'useState' hook to manage the users array:

With this change:

- The 'users' array is now managed by React's 'useState' hook.
- When you add a new user, you're creating a new array with the existing users and the new user, instead of mutating the original array.
- Since the state changes when a new user is added, the component will re-render and show the updated list of users.