useState is a React Hook that lets you add a state variable to your component.
const [state, setState] = useState(initialState)
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
const [todos, setTodos] = useState(() => createTodos());
// ...
The convention is to name state variables like [something, setSomething] using array destructuring.
initialState: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This is ignored after the initial render.
- If you pass a function as initialState, it will be treated as an initializer function. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state.
Returns
useState returns an array with exactly two values:
- The current state. During the first render, it will match the initialState you have passed.
- The set function that lets you update the state to a different value and trigger a re-render.
Caveats
- useState is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions.
example1
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
function increase() {
setCount(count + 1);
}
function decrease() {
setCount(count - 1);
}
return (
<div className="container">
<h1>{count}</h1>
<button onClick={decrease}>-</button>
<button onClick={increase}>+</button>
</div>
);
}
export default App;
example2
import React, { useState } from "react";
function App() {
setInterval(updateTime, 1000);
const now = new Date().toLocaleTimeString();
const [time, setTime] = useState(now);
function updateTime() {
const newTime = new Date().toLocaleTimeString();
setTime(newTime);
}
return (
<div className="container">
<h1>{time}</h1>
<button onClick={updateTime}>Get Time</button>
</div>
);
}
export default App;
참고문헌
'프로그래밍 > Web' 카테고리의 다른 글
Event Handling in React - How to Handle React Forms (0) | 2024.05.08 |
---|---|
Javascript ES6 Object & Array Destructuring (0) | 2024.05.07 |
React Conditional Rendering with the Tenary Operator % AND Operator (0) | 2024.05.03 |
Keeper.js 2 - how to use arrow function and prop in your project (0) | 2024.05.02 |
ES6 Arrow Functions (0) | 2024.05.01 |