Michael Curran
['Hip', 'Hip'] - A Web Dev Blog

Follow

['Hip', 'Hip'] - A Web Dev Blog

Follow
You're "React"ing Wrong (#2)

You're "React"ing Wrong (#2)

Unnecessarily passing states to your setState function

Michael Curran's photo
Michael Curran
ยทJun 11, 2022ยท

3 min read

Table of contents

photo.jpeg

You Might Be "React"ing Wrong Let's Check Out Why.


1. Intro

Welcome welcome, this is the second installment of my post series we explore some common React mistakes I have come across or made myself in React codebases. Every week we will quickly explore things that can trip you up or produce unintended results in our code. We will also mostly be focussing on React codebases. Hence the series title, You're "React"ing Wrong. Second installment of the series, we're going to check out a common misuse of drilling state.
Let's dive in!

image.jpg

2. Unnecessarily passing states to your setState function

Imagine, for example, a friends list component. Where we can add new friends in the <AddFriends /> component that update the friends array in our main <MyFriends/> component. You might be tempted to pass down your state variable for our friends array, but we actually only need the setFriends function!

For Example, You may be tempted to...

export default function MyFriends() {
  const [friends, setFriends] = useState([]);

  return (
    <div>
      <h1>Friends List</h1>
      <FriendsList friends={friends} />
      <AddFriend setFriends={setFriends} friends={friends} />
    </div>
  );
}

function AddFriend({ setFriends, friends }) {
  function handleAddFriend(event) {
    event.preventDefault();
    const name = event.target.elements.addFriend.value;
    const newFriend = {
      id: 4,
      name,
      done: false
    };
    const newFriends = friends.concat(newFriend);
    setFriends(newFriends);
  }

  return (
    <form onSubmit={handleAddFriend}>
      <input name="addFriend" placeholder="New Friend?" />
      <button type="submit">Add Friend</button>
    </form>
  );
}

3. So What? What Happens?

We are adding the new friends to the friends list array and then the setting state as we should. This will update the displayed friends in the <FriendsList /> component. However, since our new state is based off of the previous state, we don't even need to pass down the friends array.

Instead, we can access the previous friends list state by writing a function within the setState function. Whatever we return from this function will be set as the new state.

In other words, we only need to pass down the setFriends function to properly update state. Not needing to pass this state variable inevitably can greatly clean up your React codebase. Let's check out a working example next.

4. How to solve it

We can write a simple function within our setState function, this eliminates the need to pass down the current friends list variable as a prop and will clean up our code. With a simple one liner, we are able to get the same output from our code while making more readable and maintainable.

// set state based on previous state
setFriends((prevFriends) => prevFriends.concat(friend));

You can view all the code and play with the entire working example in the sandbox below.

Corrected Working Example

5. Final Thoughts & What's Next

Thanks for reading! This is the second weekly installment of my post series "You're Reacting Wrong" where we look at some common mistakes in React, why they happen, what happens, and how to avoid the mistake. So if you enjoyed this post or heck maybe you learned something new. Let us know in the comments and make sure to check back by next week when we tackle another common mistake. Or even better yet, give the blog a subscribe.

Til next time! ๐Ÿ™‚

Here are links to other posts in the series โค๏ธ
1 Check Out Last Week's Post
2 Check Out the Whole Series "You're Reacting Wrong"

Did you find this article valuable?

Support Michael Curran by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this