[React] State & Event Handling
Published: 2023-06-26 08:57:18

## 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.
<br/>

## How to use State in React
```jsx
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

<br/>

**[e.g.] Example of useState destructuring assignment**
```jsx
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

<br/>


## 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>
```

<br/>

## Event

### 1) onChange
- An event that occurs when the user's input changes

**[e.g.] When a user enters a name as an input**
```jsx
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
```jsx
 <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.

<br/>

**[e.g] Code that pops up an alert window with the name entered as an input**
```jsx
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>
    );
  };
}
```

<br/>

## 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.
```jsx
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;
```

<br/>

## Practice
[Counter.js]
```jsx
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)