DEV Community

Cover image for 4 questions I had as a React beginner
Sakura Nishiya
Sakura Nishiya

Posted on

4 questions I had as a React beginner

Introduction

When it comes to React, sometimes the logic looks super complicated, sometimes it looks super simple and clean. There are several things that made (or still make) me confused. I bumped into lots of "why?"

The problem is, even if I don't know detailed reason, somehow I can code and make something looks like "app"!
But continuing like these will bring me to be against wall someday if I want to make something more developed or complicated. I might say I am already facing obstacle right now!

Therefore, I decided to write down and organize those topics somehow I could understand after reading articles.
I'd be happy if those information can help someone.

Today, I have four questions.

  1. Why can't I use if or for inside return()?
  2. Why am I using key attribute (or something unique id) with map method?
  3. Why am I using && inside return frequently?
  4. Why React mixes with the view and the logic?

Actually, those questions are intercorrelated to each other!


1. Why can't I use if or for inside return()?

When I just started learning React, I was like this...
If I can treat variables or call functions inside return(), it's pretty natural to come up with this idea... I can write anything at least it's Javascript or TypeScrpt! I can use if or for loop! That's great!

However, as a matter of course, I got some errors when I used if statement inside return().
I wondered for few minutes, but I switched to using map method instead of if or for because I knew at least I'd get zero error and somehow it works if I use map method. Of course I didn't know why.

Only you can write inside of return are expressions that return value. That's why we cannot use if or for loop.

Instead of using if or for loop, we can use some method that return some values and we also can use operands or method chaines like .filter(...).map(...) since those return values.


2. Why am I using key attribute (or something unique id) with map method?

I was using key attribute if there is no unique id attributes in the array, because most of code that I found after googling usually use key attribute! Yes, we need something that is unique value otherwise we get some error.
Here is the reason why we always have to use unique attributes.

If we need to same elements in the same place using repetitive process, React need unique key attribute.
React use key to identify efficiently which items has changed, added or removed when it re-render. The ideal attribute as key is unique ids that are obtained by the collection, that's why using key as index is the last way especially there is a possibility to change the order of elements.

3. Why am I using && inside return frequently?

As I mentioned before, we can not use if statement, but dosen's && look working like if statement?

Before thinking about this, we have to know that some objects output nothing.
Such as

  • null
  • undefined
  • true
  • false

so, those output same ... just nothing

<div />
<div></div>
<div>{undefined}</div>
<div>{null}</div>
<div>{true}</div>
<div>{false}</div>
Enter fullscreen mode Exit fullscreen mode

We cannot use if statement. However, of course, there are some situations that we want to change the output depending on conditions.
What we do?
In this case, we use make use of behavior that boolean render nothing!

Here are the examples.

const isMorning = true

return (
 <div>
  { isMorging && <p>Good morning!</p> }
 </div>
)
Enter fullscreen mode Exit fullscreen mode
const num = 5 

return (
 <div>
  <p>`n` is { num % 2 === 0 'even' : 'odd' }</p>
 </div>
)
Enter fullscreen mode Exit fullscreen mode

Here, I am using short-circuit evaluation to substitute if statement.

What is short-circuit evaluation?

In some programming languages including Javascript, the logical operators are executed from left to right. If the first operand (which is right side) is evaluated, the language will not look (which means "short circuit") the second operand. Even though utilizing this feature, it enable us to simplify our code and to improve the performance.


4. Why React mixes with the view and the logic?

At first, I thought React was mixing view and logic in one file and it confused me more. I wondered why should I divided components or functions into so many files.

Before thinking about this, I have to talk about MVC.

What is MVC?

MVC is is a software design pattern that divide function into "model", "view", and "controller", and construct applications.

Model

The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application.

View

Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.

Controller

Accepts input and converts it to commands for the model or view.

Quoted from Model–view–controller - Wikipedia

Those components can be a circle including the users who see and use the application.

In software engineering, architecture or design patterns are thought to be existed to divide the concen. When it comes to MVC, the elements are divided by the role of technologies. This concept build a generation but that doesn't mean this is "universal truth"!

By the way, personally, this is one of the important view that I need not to forget regarding programming language or sort of technological terms. Not everything is universal truth. People in this industry discuss and deal with numerous trials and errors to somehow select the "best" way at that generation.

To return to our subject, in the history of front-end development, the view that MVC pattern does not work well is becoming mainstream.
Thus, in React, the unit of concern separation is not the role of a technology like MVC. The function of application is the unit of concern separation.

The react development philosophy is to build the applications by combining highly independent parts that are divided into functional units, and these parts are called components. To divide each parts as independent functional unit, the view and logic have to be enclosed in each parts.
*That's why we are "mixing" the view and logic in React. *

*The highly independence of the components in React can enable us to render the application pages efficiently. *
Like Rails, which has MVC pattern, render the whole page with view after the controller finishes required process. However, in React, component does required process to render itself, and rendering is done separately for each components.
For example, when you open Twitter in web browser, you can see some parts still has rotating loader even if whole layout of the page finished rendering.

The logic for components is combined with the rendering of the components. React considers it is inefficient to separate those by force.

The examples of logic for components are below

  • how to get that data to display
  • how to process the occured events
  • how the change of state effect components

Conclusion

As you can see, those questions are somehow related to each other. Through writing this post, I could find out that it is very important for me to understand each reason so that I can think about and look React at the big picture.


References:

lang:en

Short-circuit evaluation - Wikipedia
JavaScript: What is short-circuit evaluation? | by Brandon Morelli | codeburst

lang:ja

Riakuto! 2 (りあクト! TypeScript で始めるつらくない React 開発 第3.1版 【Ⅱ. React基礎編】)
JavaScriptのショートサーキット評価 - 30歳からのプログラミング

Top comments (0)