[React] State & Event Handling
Hee
Posted on June 26, 2023
State
- state: values that can change within a component
- useState: Functions that handle State in React
⭐️ React state is changed by calling a state-changing function
If you forcibly change it, re-rendering does not work, or the state does not change properly.
How to use State in React
import {useState} from "react";
const [state, useState]=useState(initial value);
- Properly name the state and the useState function that changes the state
- initial value: Set a initial value of a state
- state variable does not disappear even when the function ends
- When useState is called, it returns an array
[e.g.] Example of useState destructuring assignment
function CheckboxExample() {
//[1]
const [isChecked, setIsChecked] = useState(false);
//[2]
const stateHookArray = useState(false);
const isChecked = stateHookArray[0];
const setIsChecked = stateHookArray[1];
}
- (Destructing Assignment) [1] = [2]
◦ isChecked : variable to store state
◦ setIsChecked : Function to change state (isChecked)
◦ useState : state hook
◦ false : state initial value
Event Handling
- React event handling is similar to DOM event handling
- Events in React: use camelCase (lowercase x)
- Using JSX, passing an event handler rather than a string
HTML ) <button onclick="handleEvent()">Event</button>
React) <button onClick={handleEvent}>Event</button>
Event
1) onChange
- An event that occurs when the user's input changes
[e.g.] When a user enters a name as an input
function NameForm() {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
}
return (
<div>
<input type="text" value={name} onChange={handleChange}></input>
<h1>{name}</h1>
</div>
)
};
- The value entered as text in the input = the value of name(variable)
- An event occurs whenever the text of the input changes.
- The function setName, which changes the value of name with user input, is executed
- The input value is changed to a new state through setName
2) onClick
- Event occus when user clicks
Pitfall
<button onClick={alert(name)}>Button</button>
- If you call the alert(name) function directly in the onClick event as above, the result of the function call, not the function itself, will be applied to the onClick when the component is rendered.
- Therefore, the alert is executed when the component is rendered, not when the button is clicked, So the result, undefined (the function returns undefined when there is no return value) is applied to onClick and no result occurs when clicked.
- When passing a function to the onClick event, you must define the function inside the return statement, or define the function outside the return statement, and then pass the function itself to the event, rather than calling the function.
[e.g] Code that pops up an alert window with the name entered as an input
function NameForm() {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
//[1] Defining the function
return (
<div>
<input type='text' value={name} onChange={handleChange}></input>
<button onClick={() => alert(name)}>Button</button>
<h1>{name}</h1>
</div>
);
//[2] Passing the function itself
const handleClick = () => {
alert(name);
};
return (
<div>
...
<button onClick={handleClick}>Button</button>
...
</div>
);
};
}
Precautions when using state hooks
- Re-rendering occurs whenever the component's state changes
- If you click the checkbox, you can see that "rerendered?" is printed to the console every time you click it.
import React, { useState } from "react";
import "./styles.css";
function CheckboxExample() {
console.log("rerendered?");
const [isChecked, setIsChecked] = useState(false);
const handleChecked = (event) => {
setIsChecked(event.target.checked);
};
return (
<div className="App">
<input type="checkbox" checked={isChecked} onChange={handleChecked} />
<span>{isChecked ? "Checked!!" : "Unchecked"}</span>
</div>
);
}
export default CheckboxExample;
Practice
[Counter.js]
import React, {useState} from "react"
const Counter=()=>{
// Check if re-rendering
// Print when the Counter function is called
// console. log("Call");
const [count, setCount]=useState(0);
const onIncrease=()=>{
setCount(count+1);
};
const onDecrease=()=>{
setCount(count-1);
};
// 2nd state
const [count2, setCount2]=useState(0);
const onIncrease2=()=>{
setCount2(count2+1);
};
const onDecrease2=()=>{
setCount2(count2-1);
};
return (
<div>
<h2>{count}</h2>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
<h2>{count2}</h2>
<button onClick={onIncrease2}>+</button>
<button onClick={onDecrease2}>-</button>
</div>
)
};
export default Counter;
Digging into the Code
const [count, setCount]=useState(0)
- The useState method returns an array, and through unstructured allocation of the array
- 0th index: used as the value of the state
- 1st index: a function that changes the state value
- useState(0): 0 is used as the initial value
- Event handling: camelCase
- Re-rendering: Whenever the state of count is updated, a function(counter) returns again.
- When a component changes its state, it re-renders (calls the function again) to redraw the screen.
- In React, a component can have multiple states. If you need to write more than one state, the name of the state and the state-changing function must be different. (Declaration)
💖 💪 🙅 🚩
Hee
Posted on June 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.