React State & Handling Events

React State & Handling Events

State and event handling are key concepts in React that allow components to be dynamic and interactive. State helps manage data that changes over time, while events handle user interactions like clicks and key presses.

Understanding State in React

State is an object that holds data specific to a component. When state changes, React automatically re-renders the component to reflect the new data.

Using State in Function Components (useState Hook)

Function components use the useState hook to manage state.

Example: Counter Component

This component maintains a count value and updates it using the setCount function.

import React, { useState } from ‘react’;

function Counter() {
// useState hook: count is the state variable, setCount is the function to update it
const [count, setCount] = useState(0);

return (
<div>
<h1>Count: {count}</h1>
{/* Increase count by 1 */}
<button onClick={() => setCount(count + 1)}>Increase</button>
{/* Decrease count by 1 */}
<button onClick={() => setCount(count – 1)}>Decrease</button>
</div>
);
}

export default Counter;

📝 How useState Works

1️⃣ useState(0) initializes count with 0.
2️⃣ setCount(newValue) updates count and re-renders the component.
3️⃣ Clicking the “Increase” button calls setCount(count + 1), updating count.
4️⃣ Clicking the “Decrease” button calls setCount(count – 1), decreasing count.

Using State in Class Components

Before hooks, class components used this.state and this.setState() for managing state.

Example: Counter Component in Class

import React, { useState } from ‘react’;

function Counter() {
// useState hook: count is the state variable, setCount is the function to update it
const [count, setCount] = useState(0);

return (
<div>
<h1>Count: {count}</h1>
{/* Increase count by 1 */}
<button onClick={() => setCount(count + 1)}>Increase</button>
{/* Decrease count by 1 */}
<button onClick={() => setCount(count – 1)}>Decrease</button>
</div>
);
}

export default Counter;

📝 How Class State Works

1️⃣ this.state = { count: 0 } → Initializes count in the constructor.
2️⃣ this.setState({ count: this.state.count + 1 }) → Updates state and re-renders the component.
3️⃣ Clicking “Increase” calls increaseCount(), updating count.
4️⃣ Clicking “Decrease” calls decreaseCount

Handling Events in React

Event handling in React is similar to JavaScript but follows specific syntax rules.

Handling Click Events in Function Components

import React from ‘react’;

function ClickButton() {
function handleClick() {
alert(“Button Clicked!”);
}

return <button onClick={handleClick}>Click Me</button>;
}

export default ClickButton;

📝 Explanation

1️⃣ Define the Event Handler → The handleClick() function runs when the button is clicked.
2️⃣ Attach handleClick to the onClick event → <button onClick={handleClick}>Click Me</button>.
3️⃣ When clicked, an alert appears with the message “Button Clicked!”

Handling Click with Arrow Function

Alternatively, you can use an arrow function directly inside onClick:

function ClickButton() {
return (
<button onClick={() => alert(“Button Clicked!”)}>Click Me</button>
);
}

📌 Best for simple actions but not ideal for complex logic.

Handling Click Events in Class Components

In class components, event handlers are defined as methods, and they require proper binding when using this.

import React, { Component } from ‘react’;

class ClickButton extends Component {
handleClick() {
alert(“Button Clicked!”);
}

render() {
return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
}
}

export default ClickButton;

📝 Explanation

1️⃣ Define handleClick() as a class method → It displays an alert when the button is clicked.
2️⃣ Use bind(this) in onClick → This ensures that this inside handleClick refers to the class instance.
3️⃣ When clicked, the button triggers handleClick() and shows an alert.

Alternative: Using an Arrow Function

Using an arrow function inside onClick automatically binds this:

class ClickButton extends Component {
handleClick = () => {
alert(“Button Clicked!”);
};

render() {
return <button onClick={this.handleClick}>Click Me</button>;
}

📌 Why use an arrow function?

Arrow functions inherit this from their surrounding scope, so there’s no need for .bind(this).

Passing Parameters to Event Handlers

Sometimes, we need to pass parameters to event handlers.

Example: Passing a Name to an Event Handler

In React, you can pass parameters to an event handler using an arrow function inside onClick.

import React from ‘react’;

function Greeting(props) {
function handleClick(name) {
alert(`Hello, ${name}!`); // Fixed template string syntax
}

return <button onClick={() => handleClick(props.name)}>Greet</button>;
}

export default Greeting;

📝 Explanation

1️⃣ Define handleClick(name) → This function accepts a name parameter and displays an alert.
2️⃣ Pass props.name using an arrow function → onClick={() => handleClick(props.name)} ensures handleClick gets called with the correct parameter.
3️⃣ Clicking the button triggers an alert like: Hello, John!

Binding Events in Class Components

In class components, event handlers do not automatically bind this, so we must bind them explicitly.

Here are three common methods to bind events properly:

1. Using the constructor:

import React, { Component } from ‘react’;

class ClickButton extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this); // Binding in the constructor
}

handleClick() {
alert(“Button Clicked!”);
}

render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}

export default ClickButton;

✅ Why use this?

It improves performance because the function reference remains the same across renders.

2. Using an arrow function in render:

import React, { Component } from ‘react’;

class ClickButton extends Component {
handleClick() {
alert(“Button Clicked!”);
}

render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
}

export default ClickButton;

❌ Downside:

A new function is created on every render, which can cause performance issues in large applications.

3. Using class property with an arrow function:

import React, { Component } from ‘react’;

class ClickButton extends Component {
handleClick = () => {
alert(“Button Clicked!”);
};

render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}

export default ClickButton;

✅ Why use this?

This method automatically binds this, making it a modern and preferred way of handling events in class components.

State vs Props: Key Differences

Feature State Props
Mutability Can be changed Read-only
Scope Local to the component Passed from parent to child
Usage Used for dynamic changes Used for data flow

Conditional Rendering with State

You can conditionally render UI elements in React based on state using different techniques.

Example 1️⃣: Show/Hide Text Using useState (Function Component)

import React, { useState } from ‘react’;

function ToggleText() {
const [isVisible, setIsVisible] = useState(true);

return (
<div>
{isVisible && <p>Hello, I am visible!</p>}
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? “Hide” : “Show”}
</button>
</div>
);
}

export default ToggleText;

📝 Explanation:

•  Uses useState to manage visibility.
•  isVisible && <p>… ensures the text appears only when isVisible is true.
  Clicking the button toggles the state between true/false.

Example 2️⃣: Conditional Rendering in a Class Component


import React, { Component } from ‘react’;

class ToggleText extends Component {
constructor() {
super();
this.state = { isVisible: true };
}

toggleVisibility = () => {
this.setState({ isVisible: !this.state.isVisible });
};

render() {
return (
<div>
{this.state.isVisible && <p>Hello, I am visible!</p>}
<button onClick={this.toggleVisibility}>
{this.state.isVisible ? “Hide” : “Show”}
</button>
</div>
);
}
}

export default ToggleText;

✅ Why Use This?

  Works in older React versions (before hooks).
•  Uses this.setState to update the state

Example 3️⃣: Conditional Rendering Using the Ternary Operator

 

<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? “Hide Text” : “Show Text”}
</button>

 

🔹 This is useful when you want to change text inline.

Conclusion

State allows React components to manage and update data dynamically, while event handling enables interactivity. Function components with hooks (useState) are now the preferred way to manage state in React due to their simplicity and efficiency.

Course Video in English

Chatbot