Lecture Notes Of Day 6: State and Events in React
Objective:
Learn how to manage state in a React component and
handle events.
Outcome:
By the end of this lesson, you should be able to:
1.
Use the useState hook to manage state in a
functional component.
2.
Handle events such as clicks to update
state and trigger re-renders.
1. Introduction to State in React
In React, state refers to a variable that holds
data or information that can change over time. When state changes, React
automatically re-renders the component to reflect the updated data. This is
crucial for creating interactive UIs that respond to user input or other
events.
State can be defined and managed in two ways:
- Class
components: using this.state and this.setState().
- Functional
components: using the useState hook (introduced
in React 16.8) for managing state.
Since we are focusing on functional components, we
will work with the useState hook.
2. The useState Hook
The useState hook is used to declare state variables
in a functional component. It takes an initial value and returns an array with
two elements:
- The
current value of the state.
- A
function that updates the state.
Syntax:
javascript
Copy code
const [stateVariable, setStateFunction] = useState(initialValue);
- stateVariable:
the variable that holds the state value.
- setStateFunction:
a function used to update the state.
- initialValue:
the initial value of the state when the component is first rendered.
Example:
javascript
Copy code
import React, { useState } from 'react';
function Counter() {
// Declare a
state variable "count" with an initial value of 0
const [count,
setCount] = useState(0);
return (
<div>
<h1>Counter:
{count}</h1>
<button
onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Explanation:
1.
We declare a state variable count using useState(0).
The initial value of count is 0.
2.
The setCount function is used to update
the value of count.
3.
When the button is clicked, the onClick
event handler calls setCount(count + 1), which increments the value of count by
1.
4.
React automatically re-renders the
component with the updated count value.
3. Handling Events in React
In React, events are handled using event handlers,
just like in plain HTML. However, React uses a slightly different syntax for
binding events.
Event Binding in React:
- In
React, events are written in camelCase, such as onClick, onChange, onSubmit,
etc.
- Event
handler functions are written as JavaScript functions (not as strings).
- React
uses synthetic events to normalize events across different
browsers.
Common Event Handlers in React:
- onClick:
Triggered when an element is clicked.
- onChange:
Triggered when an input field changes.
- onSubmit:
Triggered when a form is submitted.
Example: Handling a Button Click Event
javascript
Copy code
import React, { useState } from 'react';
function ClickButton() {
const
[message, setMessage] = useState('Hello, World!');
const handleClick
= () => {
setMessage('You
clicked the button!');
};
return (
<div>
<h1>{message}</h1>
<button
onClick={handleClick}>Click Me</button>
</div>
);
}
export default ClickButton;
Explanation:
1.
We declare a state variable message with
the initial value "Hello, World!".
2.
The handleClick function is called when
the button is clicked. It updates the message state to "You clicked the
button!".
3.
The onClick event is bound to the button,
and when the button is clicked, it triggers the handleClick function to change
the state.
4. State and Events Example: Counter with
Increment and Decrement
Let’s build a simple counter component that has
two buttons: one to increment and another to decrement the counter value.
javascript
Copy code
import React, { useState } from 'react';
function Counter() {
// Declare a
state variable "count" initialized to 0
const [count,
setCount] = useState(0);
// Function to
increment the counter
const increment
= () => {
setCount(count
+ 1);
};
// Function to
decrement the counter
const decrement
= () => {
setCount(count
- 1);
};
return (
<div>
<h1>Count:
{count}</h1>
<button
onClick={increment}>Increment</button>
<button
onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
Explanation:
- We
define two functions, increment and decrement, which update the state of count
when called.
- The
onClick event handlers are attached to the respective buttons to trigger
these functions.
5. Best Practices for Using State and
Events
- Avoid
direct manipulation of state: Always use the
setter function returned by useState to update the state. Directly
modifying state variables (like count = count + 1) can lead to unexpected
behavior.
- Batching
State Updates: React batches state updates for
performance optimization, so updating the state multiple times in a single
event handler may not trigger multiple renders.
- State
Update Function: When the new state value depends on
the old state, use the functional form of the state setter to ensure you
get the most recent value:
javascript
Copy code
setCount(prevCount => prevCount + 1);
6. Summary
1.
State in React:
Use the useState hook to declare and manage state in functional components.
2.
Event Handling:
Use React’s camelCase event handlers, such as onClick, to manage user
interactions and trigger state changes.
3.
Re-rendering:
When state is updated, React automatically re-renders the component to reflect
the new state.
Exercise for Practice
1.
Create a new component that manages a
user's name as state. Add an input field and a button to update the name.
2.
Implement a toggle button that changes the
text between "ON" and "OFF" based on a boolean state.
3.
Add a button that resets the count in the
counter component back to zero.
