Urgent.News

What's breaking now, across thousands of outlets.

Tech

React useState Hook – How React Updates the UI

When I started learning React, I had a small doubt. Why doesn't React update the UI when I change a normal JavaScript variable? In JavaScript, we can easily change a variable: let count = 0 ; count ++ ; console . log ( count ); // 1 But in React, changing a normal variable doesn't update the screen. So, how do we update the UI? That's where useState comes in. What is useState? useState is a React…

When embarking on the journey of learning React, a common question arises: why doesn't React automatically update the user interface when we modify a standard JavaScript variable? In JavaScript, altering a variable is straightforward, such as `let count = 0; count++; console.log(count); // 1`. However, React behaves differently. Changes to a normal variable do not automatically refresh the screen. This is where the useState hook becomes essential.

useState is a React Hook designed to enable us to store data and trigger UI updates whenever that data changes. Let's look at a simple demonstration using a Counter component. Here is the code snippet:

```javascript

import { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0);

return (

<div>

<h1>{count}</h1>

<button onClick={() => setCount(count + 1)}>Increment</button>

</div>

);

}

export default Counter;

```

In this example, `useState(0)` initializes the state with an initial value of 0. The variable `count` stores the current value, while `setCount` is a function that updates the state. When the "Increment" button is clicked, `setCount` is invoked, requesting an update to the state. React then re-renders the component, displaying the updated value. This process is straightforward, yet it highlights a fundamental concept in React development.

Why not simply utilize a regular variable? Consider the alternative approach:

```javascript

function Counter() {

let count = 0;

return (

<div>

<h1>{count}</h1>

<button onClick={() => count++}>Increment</button>

</div>

);

}

export default Counter;

```

While the variable `count` updates successfully in JavaScript, the UI remains unchanged. The reason lies in React's inability to detect modifications to a regular variable. This is precisely why useState is indispensable. It allows React to track and manage state changes, ensuring that the user interface reflects these updates accurately.

The versatility of useState extends beyond simple counters. We can employ it with various data types, including strings, numbers, booleans, arrays, and even complex objects. For instance:

```javascript

const [name, setName] = useState('Raja');

const [age, setAge] = useState(21);

const [isLogin, setIsLogin] = useState(false);

const [skills, setSkills] = useState(['Java', 'React']);

const [user, setUser] = useState({ name: 'Raja', age: 21 });

```

These examples illustrate the flexibility of useState, enabling us to manage diverse states within a React application, such as form inputs, todo lists, login forms, and more.

An additional feature of useState is the ability to update the state using its previous value, which can be particularly useful when the next state depends on the current state. This is achieved by employing a callback function:

```javascript

setCount(prev => prev + 1);

```

In this case, `prev` refers to the previous state value, allowing for more sophisticated state management scenarios.

Reflecting on my own learning experience with useState, I grasped three critical insights. First, standard variables do not prompt React to re-render the component. Second, useState enables React to retain values between renders, preserving the state across component updates. Lastly, updating the state through the `set` function triggers React to re-render the component, ensuring the UI reflects the latest data.

Initially, I perceived useState merely as an alternative method for variable declaration. However, through practical application and deeper understanding, I recognized its pivotal role in React development.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

Isolation levels with simple examples

Your application reads that a product costs €100. Before the transaction is completed, an administrator tries to change the price to €120.

  • ReadCommitted shows changes only after commit, e.g., 100€ seen as 120€
  • ReadUncommitted allows technical reads before changes are applied, e.g., 100€ may change
  • RepeatableRead protects read rows; a price change won't affect the 100€ view

Beyond the Model: 9 Practical Engineering Hurdles in Real-Robot Imitation Learning (SO-101 + ACT)

Beyond the Model: 9 Practical Engineering Hurdles in Real-Robot Imitation Learning (SO-101 + ACT) Introduction I built this project as the final assignment for Physical AI Applied 1 at the UTokyo…

  • Power and wiring issues caused communication errors and servo problems
  • Desk layout inconsistencies led to arm touching stand leg during approach
  • Systematic data quality control ensured high-quality training data

Supabase .NET DevLog #17

Welcome to our weekly log for the Supabase .NET SDK 🎉 As explained in previous posts, the current priority is closing the feature gap between the SDK and the platform.

NetSupport RAT hits freight carriers from servers shared with a mass-mail panel

A crew is installing the NetSupport Manager remote access tool through VBS scripts whose decoys imitate freight rate confirmations and contracts of carriage.

  • NetSupport RAT infiltrates freight carriers via shared servers with mass-mail panel
  • MivoCloud and Kyonix servers host malicious software, linked by DNS name and domain purchases
  • Both delivery servers run Apache on Debian, serving kits from open directories

Security updates for Wednesday

Security updates have been issued by AlmaLinux (cockpit, dpdk, fence-agents, firefox, freerdp, gimp, opentelemetry-collector, python-dns, qemu-kvm, and raptor2), Debian (apt and squid), Fedora (ags…

More from Wednesday 4 November →