Day 5 Of React — As a Beginner

Things I’ve learned on day 5…

SriniWhoCodes
4 min readJun 11, 2023
Photo by Markus Spiske on Unsplash

Things I have learned today:

  1. Keys And Their Purpose
  2. State

1. Keys And Their Purpose

What are keys?

  • Keys are used to uniquely identify your list items.
  • Keys are required for those JSX elements directly inside a map()call always need keys!

Why do we even need keys?

  • We can use the explanation which was already given in the React Documentation itself! 👇

Imagine that files on your desktop didn’t have names. Instead, you’d refer to them by their order — the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.

File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the position changes due to reordering, the key lets React identify the item throughout its lifetime.

Things you should not do while using keys:

  • You should not use index position as a key even though React itself uses them as keys if you don’t specify the keys at all!
  • But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.

Keys rules:

  • Keys should be unique within the same array, but the same keys can be used across different arrays without any issues.
  • Keys can be a number or a string.
  • They help identify and track individual components when updates occur. When rendering a list of components, assigning a unique and stable key to each item allows React to efficiently determine which components have been added, removed, or rearranged.
  • If keys are generated dynamically or change frequently during rendering, it can lead to unintended consequences.
  • Changing keys during rendering can cause components to be unnecessarily unmounted and remounted, leading to performance issues and potential loss of component state.
function TodoList() {
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' },
{ id: 3, text: 'Deploy to production' },
];

return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}

function TodoItem({ todo }) {
return <li>{todo.text}</li>;
}

export default TodoList;

Note: Keys are not inside the props. Each list will have ‘key’ property by default.

2. State

  • State in React is useful for you to change values/states of the JSX or Component’s.
  • You can ask “Well, I can use the event handler functions for this right?”. Well, you’re not completely wrong.
  • You can add the event handlers to an element (a button).
  • If you click a button then the content of another HTML tag (<p>) should change. But if you try to modify <p> using the event handlers alone, then it won’t work in React.
  • This is just because React is not designed in that way!
    (NOTE: There’s a bit of explanation that I must address but I’ll cover it tomorrow with the lifecycle of a state.)
  • You should use React’s hooks for this kind of issue. And that is useState().
  • useState() will return an array which contains two things.
  • A state variable — to retain the data between renders.
    A state setter function — to update the variable and trigger React to render the component again.
  • However, inside the parentheses you need to put only one argument and that is the Intial Value.
  • Here’s the code that I’ve written now:
function Counter() {
let [count, setCount] = useState(0);
const onIncrementHandler = () => {
setCount(++count);
};
const onDecrementHandler = () => {
setCount(--count);
};

return (
<div>
<h1>Counter App</h1>
<button
className="increment"
onClick={onIncrementHandler}
>
+
</button>
<h2>{count}</h2>
<button
className="decrement"
onClick={onDecrementHandler}
>
-
</button>
</div>
);
}
  • The Counter component is a basic counter application. It maintains a count value using the useState hook from React.
  • The component renders a heading displaying “Counter App” and two buttons. The first button is labeled “+” and the second button is labeled “-”.
  • When the “+” button is clicked, the onIncrementHandler function is triggered. This function updates the count state by incrementing it using the ++count syntax, and then sets the updated value using the setCount function.
  • Similarly, when the “-” button is clicked, the onDecrementHandler function is triggered. This function updates the count state by decrementing it using the --count syntax, and then sets the updated value using the setCount function.
  • The current value of the count is displayed within an <h2> element in the component.
  • This component allows the user to increment and decrement a count value by clicking the respective buttons, and the updated count is displayed on the screen.

That’s a wrap for now…🚀

Tomorrow I’ll cover the concepts of keys, useState() and other related stuff.

I hope you find this blog useful. If you did then make sure to let me know by commenting, clapping and sharing this blog to your friendly developers!

Bye…😁🤟

Resources That I’ve Used For This Blog:

  1. Keys — https://react.dev/learn/rendering-lists
  2. State and Event Handlers — https://react.dev/learn/adding-interactivity

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

SriniWhoCodes
SriniWhoCodes

Written by SriniWhoCodes

I write about Web Development and other related stuffs.

No responses yet

Write a response