paint-brush
Here's Why You Need to Use a Front-end Frameworkby@hacker7182015
505 reads
505 reads

Here's Why You Need to Use a Front-end Framework

by Hassan DjirdehMarch 7th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

To answer the question directly — you don’t. It's important to remember that web browsers don’t understand the syntax from tools like React, Vue, Angular, etc. — they can only parse HTML, CSS, and JavaScript to build a webpage. If you want to stick with using only the native web application languages, you can very well do so. However, using a front-end framework can make web development much easier and much more efficient.
featured image - Here's Why You Need to Use a Front-end Framework
Hassan Djirdeh HackerNoon profile picture

Previously, we did a deep-dive tutorial on building a custom Q&A chatbot with React, Node.js, and OpenAI. In the next set of posts, we'll be going back to discussing more front-end engineering-specific topics and today we'll begin by looking to answer the age-old question: "Why do I even need to use one of these shiny new front-end frameworks?".



To answer the question directly — you don’t. It's important to remember that web browsers don’t understand the syntax from tools like ReactVueAngular, etc. — they can only parse HTML, CSS, and JavaScript to build a webpage. If you want to stick with using only the native web application languages, you can very well do so. However, using a front-end framework can make web development much easier and much more efficient.

With vanilla JavaScript, adding interactivity to a webpage can only be done through query selectors and event listeners. We select elements on the page with query selectors and use event listeners to handle user interactions with those elements.

As an example, assume we have markup like the following to create the template of a form:

<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" />

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" />

  <input type="submit" value="Submit" />
</form>

When it comes to introducing interactivity, we need to access DOM elements in our HTML (with query selectors and event listeners) to introduce the interactivity that we would want.

Here is an example of how we can use native JavaScript to interact with the form template shared above:

let form = document.querySelector('form');
let nameInput = form.querySelector('#name');
let emailInput = form.querySelector('#email');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  let name = nameInput.value;
  let email = emailInput.value;
  console.log(`Name: ${name}, Email: ${email}`);
});

The above code adds an event listener to the form which listens for a submit event. When the form is submitted, the code retrieves the values entered in the input elements and logs them to the console.


You can try out the above on Stackblitz here.


The above works well for simple scenarios but things can get difficult to manage quickly. As the complexity of a web application increases, the number of elements on the page and their associated states can grow quickly.

For example, imagine a large complex web application, like Facebook, that provides a wide range of features for users — including news feeds, messaging, groups, events, and more. The user interface logic of an application like this can be very complex, with different components and elements representing various aspects of the user's interaction with the site.

React

This is the history behind why the React JavaScript library was created. As Facebook's web application grew, the engineers in the company needed a way to manage the state of the application in a more efficient and scalable way. To solve this problem, Facebook engineer Jordan Walke created React.

React provided a new declarative way of building user interfaces by having developers describe what the program should do, rather than how it should do it. There are many ways React allows for this, such as:

- The UI of a web app is broken down into smaller reusable components.

- Components are pure functions which means that their output depends only on their input.

- When the state of a React component changes, the library automatically re-renders the component and updates the Document Object Model (DOM) to reflect the new state. No more do we need to query select and manipulate the DOM manually to update the view.

- And more...

Though I highlight React as an example of a front-end framework, pretty much all new front-end frameworks today share a very similar philosophy with minor differences between them. They all have the same core concepts of components, state, props (i.e. state passed from parent to child), declarative-style programming, etc.

Let's go through the above form example we had earlier but instead look to build it up with React. We'll look to first create a component and to do so, we need to define a function to describe the component name. As an example, we can define a function name of 

Form()
 to describe that we’re building a form component.

function Form() {}
Note: React component names should always start with a capital letter!


To make a function a React component, it needs to return markup. With React, we’re able to do this with JSX, a syntax extension for JavaScript that allows us to write HTML elements within our JavaScript code. Here’s how we can have our 

Form()
 function return the markup of an HTML form.

function Form() {
  return (
    <form>
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" />

      <label for="email">Email:</label>
      <input type="email" id="email" name="email" />

      <input type="submit" value="Submit" />
    </form>
  )
}

With that, we’ve created our 

<Form />
 React component.

We saw earlier, in our standard JavaScript example, how we have to use query selectors and event listeners to add interactivity to our web elements. With React, however, we can achieve this by using state and props to manage the data and interactivity of our components.

State is an object that represents the data or information that a component needs to maintain and update. It allows a component to keep track of changes and respond to user interactions. We’ll look to replicate the form behavior we created in standard HTML and JavaScript in our React component with the help of component state.

For our 

<Form />
 component, we can create a state object labeled formData to track the value entered in the inputs of our form. We’ll do this with the help of the 
useState()
 function Hook that will give us a 
formData
 object and 
setFormData()
 function that we can use to update state.

function Form() {
  // creating state object
  const [formData, setFormData] = React.useState(
    { name: "", email: "" }
  );

  return (
    <form>
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" />
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" />
      <input type="submit" value="Submit" />
    </form>
  )
}

Within our component, we can define two new functions:

-

handleChange()
: this will be used to update the values of the input fields in our form.

-

handleSubmit()
: this will be used to submit the form.

function Form() {
  // creating state object
  const [formData, setFormData] = React.useState(
    { name: "", email: "" }
  );

  // handle change in our form inputs
  function handleChange(e) {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  }

  // handle form submit
  function handleSubmit(e) {
    e.preventDefault();
    console.log(formData);
  }

  return (
    <form>
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" />
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" />
      <input type="submit" value="Submit" />
    </form>
  )
}

Our 

<Form />
 component now behaves as we expect.


You can try out the above on Stackblitz here.


Our form written in React behaves almost identically to the form we created earlier with standard Javascript and HTML. However, there is a key distinction as to how we’ve implemented each form.

With standard JavaScript and HTML, we used query selectors and event listeners to add interactivity to our form.

With React, we achieved this by building our JavaScript logic into our component since components allow us to couple HTML and JavaScript together. In other words, we used a more declarative approach to building out the user interface (UI)!

Closing thoughts

- React isn't the first JavaScript/front-end framework to come into the scene. There has been tools like knockout.js, ember.jsangular.js, etc. that came before React to make front-end engineering more maintainable. However, React introduced many new concepts that are now widely recognized in many of today's newer frameworks and libraries.

- I recognize today's email was more of an introductory discussion. For the next couple of weeks, I'll be diving a bit deeper on topics like React Hooks, using Forms in React, and best practices when using React and TypeScript.

- If you're interested in a deep-dive into the history behind React and how it was created, check out React.js: The Documentary on YouTube. I haven't finished the documentary myself but it's a great watch!

- Subscribe to https://www.frontendfresh.com/ for more discussions like this to hit your inbox on a weekly basis!

 This article is the third article sent to the frontendfresh.com newsletter. Subscribe to the Front-end Fresh newsletter to get front-end engineering tips, tutorials, and projects sent to your inbox every week!

Also published here.