DEV Community

Cover image for Week 4: The Why and How of React 💡
Nikhil Sharma
Nikhil Sharma

Posted on

Week 4: The Why and How of React 💡

Now to freshen myself up, I have decided to delve into some frontend for the next few weeks. Hence, this week I understood the Why and How of React. Let's get right into it!

Topics Covered✅

This week I covered a few things, some small individual topics but majorly I wanted to cover some React to change my flow up a little. But for that, I first had to know why do we need React at all? And secondly, how does React do what it does?

The things that I learned about this week were as follows-

  • Connecting a frontend to a backend
  • Debouncing & Throttling
  • The need for React

1. Connecting a frontend to a backend📎

I was surprised that I hadn't thought about this thus far. But once I learned about it, it felt so intuitive. The way you connect a back-end to a front-end is rather simple.

You just put different fetch calls in you front-end code to the different endpoints in your back-end code. To test this locally, I would just host the back-end on a terminal with Express.js and open my index.html file.

It was such a simple concept, yet surprisingly fascinating.

2. Debouncing & Throttling

These are two important performance optimization techniques. Both are ways to control how often a function runs, especially when triggered by continuous user actions like typing, scrolling, or resizing.

Debouncing ensures that a function executes only after a certain period of inactivity. For example, when a user types in a search bar, the API call will fire only after they stop typing for a moment instead of on every keystroke.

This is how I coded a very raw debouncing function-

    let timeout;
        function debounced(){
            clearTimeout(timeout);
             timeout = setTimeout(() => {
                calcSum();
            }, 1000);            
        }
Enter fullscreen mode Exit fullscreen mode

I found this very interesting. What I am doing here is that, I declared a timeout variable which is supposed to hold the ID of the setTimeout that we use to measure the time between two requests.

If we get a request, setTimeout is used and the timeout variable gets its ID. If we do not get any more requests for the next 1 second, then the calcSum() function is called and the program continues. However, if we do get another request in 1 second, then the clearTimeout function is called and the fetch request(or the function call in this case) is not sent.

Throttling, on the other hand, ensures that a function runs at most once in a specified time interval, no matter how many times the event is triggered.

I found this interesting because, unlike debouncing, throttling doesn’t wait for inactivity — it ensures regular execution at a controlled pace. This is super useful for things like scroll listeners, mouse movements, or window resize events, where you want frequent updates but don’t want your function to fire hundreds of times per second.

3. The need for React

To realise the importance of React, let's consider a small project.

Say we have a simple todo project. The user can add todos which update on the screen and they can also mark todos as done. Say we just store the todos in a simple local variable for now, which we call the state variable. Every time the user adds a new todo, we add it to the state variable and then update the state variable on the DOM.

A more optimal way to do this would be to calculate the diff between the current state variable and the previous state variable and then just changing that on the DOM.

 <div id="todo-list"></div>
<input type="text" id="todo-input" placeholder="Add todo"/>
<button id="add-btn">Add</button>

<script>
let state = [];
let prevState = [];

const todoList = document.getElementById('todo-list');
const input = document.getElementById('todo-input');
const addBtn = document.getElementById('add-btn');

function renderDiff() {
  // Simple diff: find new todos
  const newTodos = state.filter(todo => !prevState.includes(todo));

  newTodos.forEach(todo => {
    const li = document.createElement('div');
    li.textContent = todo;
    todoList.appendChild(li);
  });

  // Update prevState
  prevState = [...state];
}

addBtn.addEventListener('click', () => {
  const todo = input.value.trim();
  if (todo) {
    state.push(todo);
    renderDiff(); // only adds new items to the DOM
    input.value = '';
  }
});
</script>
Enter fullscreen mode Exit fullscreen mode

Imagine scaling this up, where we have tens of such state variables for different DOM elements.
Then this diff calculation gets quite DSA heavy and can get very complicated. That is where React comes in. React basically calculates that diff for us under the hood very easily by maintaining a virtual DOM and thus, the code is simplified as follows.

 import React, { useState } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = () => {
    if (input.trim()) {
      setTodos([...todos, input]);
      setInput('');
    }
  };

  return (
    <div>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Add todo"
      />
      <button onClick={addTodo}>Add</button>

      <div>
        {todos.map((todo, index) => (
          <div key={index}>{todo}</div>
        ))}
      </div>
    </div>
  );
}

export default TodoApp;
Enter fullscreen mode Exit fullscreen mode

I will be getting more into the details of this code when I delve deeper into it next week! For now, this is where I decided to stop.

New things I learnt this week🔄

  • Debouncing and Throttling for performance optimisation.
  • What React does under the hood! ## Wrapping up! The volume of content I covered this week might have been lesser than the average week, but the topics I covered were very interesting to me, which is also important if we wish to stay consistent. If you have any questions or feedback, make sure to comment and let me know!

I'll be back next week with more. Until then, stay consistent!

Top comments (0)