React Part 2: Meet JSX and the Quirky Misadventures of map()

React Part 2: Meet JSX and the Quirky Misadventures of map()

Hey I am back …

Well I am going to talk about my syntax . It may seems like I am talking about my girlfriend but actually its is NOTTTTT. So her name is JSX. Well she is pretty amazing ??. She is always there for me .

  • Well in your language it is the syntax in React. As I mentioned before, create-react-app has already bootstrapped a boilerplate application. All files come with default implementations. Let’s dive into the source code.
  • Last day we created an application named smily. Let look at the App.js file inside the src folder. Hey its fine the names may seem complicated but trust me I am not complicated ??

  • Don’t let yourself get confused by the import/export statements and class declaration. These features are already JavaScript ES6
  • Hey wait a sec I forgot to tell about ES6.
  • So ES6 stands for ECMAScript 6. ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

So lets get back to our code

  • First, this React component, called App component, is just a JavaScript function.
  • It’s commonly called function component
  • App component doesn’t receive any parameters in its function signature yet
  • Hey don’t worry we will put something there later ??
  • App component returns code that resembles HTML which is called JSX
  • Let us define a constant say title and assign it to react

  • The above code is a simplest version of a react code and see we also defined a constant title
  • Run the above code
  • Hey btw you can run my code simply by typing this command

npm start        

  • This is a secret spell in my application
  • When you cast this spell via your terminal (Provided you in the same location as the project) Then magically a window will pop up .
  • This window will show you the result of the code . Why don’t we get our hands dirty


  • When you run react app for the first time then you will see a spinning react logo.
  • Well this happened because create-react-app gives you everything to get started with . So it also has some dummy code

This is clearly visible if you check the App.js Code

  • There they imported a logo.svg which is that rotating logo
  • They used this logo in the img tag
  • And the style is given in the App.css file
  • Forget the rest

Now let us alter this code to print a simple Hello World

Change the code as shown

  • Now the page will look like this
  • Damm seeee we did something in react
  • Now lets come back to JSX
  • So earlier I told you to create a constant title name react
  • Let us understand JSX a lil more with the help of that constant
  • Lets print that variable



  • Remember, everything in curly braces in JSX can be used for JavaScript expressions
  • Just like how we printed Hello World using React
  • JSX was initially invented for React, but it became useful for other modern libraries and frameworks after it gained popularity.
  • It is one of my favorite things about React.
  • Without any extra templating syntax (except for the curly braces), we are now able to use JavaScript in HTML.


Now let me talk about my List Feature

  • So ig at this point all of you are aware about the list concept
  • Lists are used to display data in an ordered format
  • An example of creating a list is as shown below

const numbers = [1, 4, 9, 16];        

  • How can we iterate through this
  • Well there are several ways but one of the most commonly used method is shown below

  • Wait a second where did this map function came from
  • No worries I will explain
  • The?map()function is used to iterate over an array and manipulate or change data items. In React, the?map()function is most commonly used for rendering a list of data
  • So here we will manipulate the list numbers via multiplying 2 with the elements
  • If we use this concept we can extend a little more as shown below

  • Here we defined a list and used the map function to iterate as shown and get the title value
  • Instead of writing it with list.map(function(item){})} well this seems to be complicated so in modern js we can change this to something called arrow functions

list.map(()=>{})        


In the above code using map there is a critical problem . That is we have not mentioned key attribute. Hmm why we should right ... Let us understand why key is important

The Misadventures of map(): When Array Methods Go Rogue

Ah, map()! Our trusty sidekick in the world of JavaScript. Like a reliable but quirky friend, it's always there to help us transform our arrays into something new. But beware, fellow coder! map() can sometimes be more of a prankster than a pal. Let’s take a tour through the comical mishaps that can occur when you trust map() a little too much.

I will point out some drawbacks of this map function

The Great Key Mystery

  • You’re at a party, introducing guests to one another. Everyone needs a name tag (a key) so you can tell them apart. You hand out blank name tags and tell everyone to just write "Guest" on them. Oops! Now, every time you call out "Guest," everyone answers. Chaos ensues.
  • This means if all have same name tag you cannot identify them
  • In React, when you use map() to create lists, you need unique keys for each element. Forget this, and React will throw a fit, yelling about non-unique keys.
  • Think of React as a detective with a sharp eye for changes. Its job is to keep your app looking fresh and up-to-date without unnecessary effort. This detective work happens through something called the "diffing algorithm," which helps React figure out the minimum number of steps needed to update the real DOM.
  • Key attribute is important to track the changes in the list. If we not keep track of changes in the list then it ends up updating more things than necessary, like that friend who insists on rearranging the entire living room just because one pillow was out of place.
  • Okay then why don't we use index as a unique key . Well from our pov index is unique right & no two elements will have same index right ?

const items = ['apple', 'banana', 'orange'];
const listItems = items.map((item, index) => <li key={index}>{item}</li>); // Bad practice!        

Why the above code is bad if the data is not static

  • If we append something in this list no issues will happen everything works perfect
  • But if we add something at the beginning then things will change because the index will change
  • If the index changes then it needs to re-render again . Earlier only the last element changed so React just need to change that because rest of the things are the same.
  • It is like React has to do a full-on makeover! Before, only the last element got a new outfit, so React just updated that one. But now, since we added something at the beginning, React’s like, 'Whoa, everything’s different!' and decides to redecorate the whole room.

Synchronous Snail

  • Imagine map() as a chef in a restaurant, preparing dishes one by one, meticulously. This chef never multitasks. One customer wants a salad, another wants a seven-course meal. The chef takes their sweet time with each dish, and the queue outside is getting restless.
  • map() executes synchronously, which is like saying, “Hey, wait here while I transform every single item in this massive array.” For small tasks, it’s fine. But give it a big list, and suddenly the party’s over. Your UI freezes, and your users start remembering they have other things to do.

const largeArray = new Array(100000).fill(0);
const doubledArray = largeArray.map(num => num * 2); // UI might freeze for large arrays!        

The Memory Hog

  • Imagine map() as a squirrel, gathering nuts for winter. It grabs a nut, transforms it into something shiny, and stores it. But if it tries to transform an entire forest's worth of nuts, suddenly there’s no more room. The squirrel’s tree (your memory) is full, and the squirrel (your program) just freezes.
  • map() returns a new array. If the original array is massive, and you’re running map() inside a component that re-renders often, you’re piling up data like there’s no tomorrow. Next thing you know, your app is slower than a snail on vacation.

const largeArray = new Array(1000000).fill(0);
const processedArray = largeArray.map(item => item + 1); // High memory usage        

  • If you need to transform massive data sets, consider using libraries that can handle large arrays efficiently, like lodash, or use streaming techniques to process data chunks.

Using map() for Side Effects: The Party Crasher

  • You invite map() to a function. “We’re just looping over an array,” you say. “What could go wrong?” But map() isn’t a simple guest. It shows up, expecting a transformation and a new array to take home. Instead, you’re just printing values to the console, and map() is standing there, wondering what’s happening.
  • map() is for transformation, not for side effects like logging to the console or updating state. Using it for side effects is like using a chainsaw to butter toast. Sure, it works, but it’s overkill, and now you’ve got butter everywhere.

const items = [1, 2, 3];
items.map(item => console.log(item)); // Misusing map() for side effects        

  • Use forEach for this

const items = [1, 2, 3];
items.forEach(item => console.log(item)); // Perfect for side effects        

Conditional Rendering Gone Wrong

  • map() walks into a room, looking to transform every guest. But wait! Only guests wearing blue should be transformed. Now, map() is confused. It still visits everyone, leaving empty chairs for those not in blue. The room looks weird, and half the chairs are empty.
  • map() applies to every element. If you use it for conditional rendering, you end up with null or undefined in places where you didn’t want anything at all. The result? A cluttered and inefficient UI.

const items = [1, 2, 3, 4];
const listItems = items.map((item) => item > 2 ? <li key={item}>{item}</li> : null); // Inefficient        

  • Use filter

const items = [1, 2, 3, 4];
const listItems = items.filter(item => item > 2).map(item => <li key={item}>{item}</li>); // Clean and efficient        

End of Part 2

So far we learned about the basic setting up of react and about JSX and understood the map function. We will continue the rest in the coming parts


References


要查看或添加评论,请登录

社区洞察

其他会员也浏览了