DEV Community

Andrew Lee
Andrew Lee

Posted on • Updated on

Top 4 Mistakes in React Interviews

These are four common mistakes in React interviews. Sometimes the pressure of the interview makes us make silly mistakes. Hopefully reviewing this post will help before your next interview.

1. Map

When we have to render a list of items, we can use map within JSX.

<>
  {list.map((item) => {
    return <p key={item.id}>{item.name}</p>
  })
</>
Enter fullscreen mode Exit fullscreen mode

We can use this shortened syntax too which lets us omit the return.

<>
  {list.map((item) => (
    <p key={item.id}>{item.name}</p>
  ))
</>
Enter fullscreen mode Exit fullscreen mode

However, many candidates forget to return inside of the map and get frustrated why the list isn't rendering.

<>
  {list.map((item) => {
    <p key={item.id}>{item.name}</p>  // need to return here
  })
</>
Enter fullscreen mode Exit fullscreen mode

It's hard to locate this typo in an interview sometimes.

2. Updating Arrays and Objects

Whenever we mutate an array or object that's stored as a React state, we have to create a new instance. We run into errors when we mutate the state directly.

A part of me feels like this should have been abstracted away from developers completely so that we can just mutate the array. I made a cheatsheet on how to update arrays and objects in React: https://dev.to/andyrewlee/cheat-sheet-for-updating-objects-and-arrays-in-react-state-48np

3. Making a network call

The fetch API is a tricky one to remember/implement on the spot during the interview, especially if we are used to using different libraries.

Sometimes, we have to do a quick fetch an API and it might seem silly to reach for a third party library. Remember fetch returns a promise of its response, and we have to convert it into JSON before we can read from it.

const res = await fetch("https://someurl.com");
const json = await res.json();
Enter fullscreen mode Exit fullscreen mode

To make a request when the component loads we can do something like the following:

const SomeComponent = () => {
  const [list, setList] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch("https://someurl.com");
      const json = await res.json();
      setList(json);
    };
    fetchData();
  }, []);

  return (
    <>
      {list.map((item) => {
        return <p key={item.id}>{item.name}</p>
      })
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Fetch the data inside of a useEffect and update the state that we want to iterate over. await cannot be directly used inside of a useEffect so we have to create an async function first and then call it.

4. On click on a list item

Sometimes we have to render a list of items that mutates the state of the parent element. For example lets say we have a list of todo items. When we click on one of them we have to update the state in the parent.

Sometimes candidates get stuck on when happens on the onClick. How do we know which item was clicked?

<>
  {list.map((item) => {
    return (
      <button
        key={item.id}
        onClick={onItemClick}
      >
        {item.name}
      </button>
    );
  })
</>
Enter fullscreen mode Exit fullscreen mode

We do this by passing in the item to the click handler:

<>
  {list.map((item) => {
    return (
      <button
        key={item.id}
        onClick={() => onItemClick(item)}
      >
        {item.name}
      </button>
    );
  })
</>
Enter fullscreen mode Exit fullscreen mode

Discussion (10)

Collapse
lukeshiru profile image
LUKESHIRU • Edited on

A few things:

  • 3. Making a network call: One thing that is quite important (even more than if they use a library or not, because if the interview is well structured then they can use whatever library they want) is that those kind of functions should be called in a useEffect and not directly in the render. Is either that or use some library that does that for them.
  • 4. On click on a list item: There are several approaches to the same issue, a few that came to mind:
// Using dataset:
list.map(({ id, content }) => (
    <p key={id} data-id={id} onClick={onItemClick}>
        {content}
    </p>
));

// And then...
const onItemClick = ({ currentTarget }) =>
    console.log(`Clicked id: ${currentTarget.dataset.id}`);

// Or using currying:
list.map(({ id, content }) => (
    <p key={id} onClick={onItemClick(id)}>
        {content}
    </p>
));

// And then...
const onItemClick =
    id =>
    ({ currentTarget }) =>
        console.log(`Clicked id: ${id}`);
Enter fullscreen mode Exit fullscreen mode

Also, I think I believe you omitted and I believe is even more common than the ones you mentioned: Don't forget about the key property when mapping. A pretty common mistake is to do lists like this:

list.map(item => <p>{item}</p>);
Enter fullscreen mode Exit fullscreen mode

Ideally every item should have an unique identifier and use that to identify it when looping to avoid rendering issues:

list.map(({ id, content }) => <p key={id}>{content}</p>);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
rkallan profile image
RRKallan

I would never use a different tag other then button for clickEvents.
When using button there is no need to use the data attribute, there you can use the value attribute

My suggestion would be use button and value attribute
Or create for button a separate component

Collapse
andyrewlee profile image
Andrew Lee Author

These are great points! I'll update the article with your suggestions.

Collapse
ronicastro profile image
Roni Castro • Edited on

I believe the code on problem 3 will not work, because 'await' is only allowed within async functions.
This would work:

  useEffect(() => {
    const fetchData = async () => {
         const res = await fetch("https://someurl.com");
         const json = await res.json();
         setList(json);
     }
    fetchData();
  }, []);
Enter fullscreen mode Exit fullscreen mode
Collapse
andyrewlee profile image
Andrew Lee Author

Yup! Fixing it now..

Collapse
anatame profile image
Anatame

Bruh, these are like too newb things.

Collapse
andersbjorkland profile image
Anders Björkland

These are some nice little hurdles. Have you done these yourself ever once in a while?

For myself, I think the reducer pattern is my weak spot. Redux with classes works fine for me, but doing it the functional way... O boy, I should do this more often!

Collapse
akashsingh profile image
AKASH SINGH B • Edited on

This is so much informative. Thank you

Collapse
abhishekraj272 profile image
Abhishek Raj

Never add onClick on each element unless necessary.

Put onClick on parent element and use Event Bubbling and Event Capturing.

javascript.info/bubbling-and-captu...

Collapse
lukeshiru profile image
LUKESHIRU

React does event delegation for you (with Synthetic events)! When you add a listener in React, that listener is actually pulled to the top (the root element). So this optimization you suggested doesn't apply here.