DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > The First Steps to Understanding React

The First Steps to Understanding React

Just beginning to code with React? Learn the most important concepts to start leveraging React to its fullest potential.

Enrique Molinari user avatar by
Enrique Molinari
·
Jan. 16, 22 · Web Dev Zone · Tutorial
Like (3)
Save
Tweet
5.65K Views

Join the DZone community and get the full member experience.

Join For Free

In this post I will give you - what I think - are the most important concepts to start dominating React.

For years we have seen back-end programming languages evolve. Evolve to accommodate new features and tools towards making software maintainable. From syntactical constructions like classes and objects, to namespaces, packages and modules. With great tools like those that help you to manage dependencies (maven, gradle, composer, pip, gems, etc) and those to automate the testing. Aligned with these, the software development community writing books and articles about best practices, patterns, refactoring techniques plus different proposals about how to architect your application: layered, modular, hexagonal (clean), onion, modular monolith, SOA, event-driven, microservices, etc.

On the other hand, at the front-end, we did the best we could. With almost zero tools or bibliography related to helping us write maintainable software. Most of us had to deal with a server-side template engine (PHP, JSP, JSF, freemarker, etc), mixing HTML, CSS, and jquery. At some point, JavaScript was considered a serious language thanks primarily to GMail, which shows how powerful a (single-page) Web application can be.  With the community screaming for better tools, Node.js proposed server-side JavaScript, and a tool to manage dependencies was created (npm). In addition, the Javascript language, in the ES6 release, evolved with many new features, especially the addition of modules. 

Taking advantage of these improvements, React was released incorporating to the front-end the idea of building applications by assembling self-contained components.  Does it sound that nothing really new was added? You are correct, we have been reading for years about the “self-contained components” silver bullet in those old books about software engineering. However, I believe React developers have done a great job providing the tool to make this real. In React, you design applications by assembling components, which are built by using plain JavaScript functions. 

The people behind React’s design decisions have challenged very established patterns like MVC, where you have the display logic and the markup separated in different abstractions. In React you have the display logic (fetching data, event handling, etc) and the markup in the same abstraction: the component. And each component represents a fragment of the functionality of your View. This is what makes React so great and the reason I love it. 

Without the details (that you should learn if you want to start coding in React), by using some pseudo-React code, let me explain to you the idea of how to build an application by assembling components. 

Suppose we want for our application a pretty simple layout, with a menu header and a body that contains a list of tasks like shown on the figure below:

Task list sample application                                                        Figure 1: Task List Sample Application

With this in mind, we are going to craft two components: Menu and TaskList. The Menu component will be responsible for building the top header with the label “Task List”. And the TaskList component will have the responsibility of obtaining and displaying the task list.

In your Rect application entry point (usually the App.js component), you can write something like:

JSX
 
function App() {
 return (
  <div>
    <Menu />  
    <TaskList />
  </div>
 );
}

The function above represents the main component called App. What that function component returns is called JSX (JavaScript XML). A JavaScript extension was proposed by React to paint the UI. What we are doing with the App component above is to instantiate the Menu and TaskList component (to use a term known from OOP). In other words, we are asking React to render these components, in that order (first Menu, then TaskList) as children of a <div> element. The Menu component paints itself as a <header> element, see below:

JSX
 
function Menu() {
 let title = “Task List”;
 return (
   <header>
     <span>{title}</span>
   </header>
 );
}

Note from above, the variable title in curly braces in JSX. You can wrap any JavasScript expression between them.  Let’s continue reviewing how the TaskList component gets the task and displays them:

JSX
 
function TaskList() {	
  let tasks = initializeState([ ]);          

  function afterFirstRender() {
     fetch(“https://my.endpoint.com/tasks”)
       .then((response) => response.json())
       .then((json) => setState(json));
  }

  return (
   <section>
    <p>Tasks List</p>
    <table>
     <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Expiration Date</th>
     </tr>
     {tasks.map((aTask) => (
     <tr>
      <td>{aTask.id}</td> 			
      <td>{aTask.name}</td>
      <td>{aTask.expirationDate}</td> 
     </tr>		
    ))}
   </table>
  </section>
 );
}

Like objects in OOP, React components have a state and a set of functions associated with their lifecycle. For instance, in OOP, the constructor is called at creation. If you look at the TaskList component above, in the first line we are initializing its state,  with an empty array. We then define a function called afterFirstRender and then the return statement of the component’s function. The first thing React does is to render the component (by invoking the component’s function), which means, processing the JSX (transforming it into HTML) and inserting the transformation into the DOM. At that point, the tasks state variable is still an empty array.  If we pause the execution right now, we will notice by looking at the browser, that the component has been rendered. Looking like in the image below:

Empty Table task list

                                                                         Figure 2: Empty Table

After the rendering is finished, the afterFirstRender function is invoked by React (this is one of the lifecycle functions). This function, by using the JavaScript fetch function, obtains the tasks from an API, transforms them into JSON, and saves them into the tasks state variable, using the especial setState function. This special function, after assigning the value to the variable, triggers the re-render of the component, painting the cells of the <table> with the task data (since now the tasks state variable has been updated). And now, if we look at the browser we will see what is shown in figure 1. Please, note how nice this was. TaskList is really a self-contained component. It was able to get the data from an API and to paint itself into the DOM.  

These were what I consider the main concepts you should learn if you want to start coding in React: self-contained components, JSX, State, and lifecycle functions. There are many other and more examples you can find in the book Understanding React.

React (JavaScript library) Web application Software development Task (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • AWS Serverless Lambda Resiliency: Part 1
  • 3 Predictions About How Technology Businesses Will Change In 10 Years
  • Top 10 Criteria to Select the Best Angular Development Company
  • Salesforce and Snowflake Native Data Integration Options

Comments

Web Dev Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo