Overview
useState Hooks is used when managing a state value of React component.
State value can be understood as something like a local variable of React component.
Therefore, even if the same component is used, the internal state value is managed separately for each component.
const [value, setValue] = useState(initialValue);
The syntax is like the above code.
The useState Hooks returns state value as the first element and state changing function as the second element.
As you already know, you can write down the value and setValue as you want in the sample code.
Conventionally you need to use camel case naming and add a prefix set to the function.
You have to set the initial value at the initialValue in the sample code.
And, following the functional programming philosophy, it is recommended to use const variable when you use the useState Hooks.
Description
React re-render certain components when the state changing function is called. At this time, its child components are also re-rendered.
It can induce performance drop, you can use useMemo Hooks for optimization.
React handles in state values in batches as possible.
If it handles synchronously whenever the state value is changed, it is rendered each time. And it is the cause of performance degradation.
Therefore, it seems the reason React handles batch as possible.
The state changing function is called asynchronously, but its order is guaranteed.
Usage
Let's make a simple counter as an example.
You can simply use an online IDE like codesandbox.io.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1>Current Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)}>Decrease</button>
</div>
);
}
I create a state variable count using useState Hooks. And it will show in an h1 tag.
I create two buttons for increasing and decreasing the counter.
If you click the button, it calls state changing function.
You can also put a function into the state changing function.
<button onClick={() =>
setCount(prev => prev + 1)}
>Increase</button>
'Web > JavaScript' 카테고리의 다른 글
[JavaScript] Callback, Promise, Async/Await (0) | 2020.09.18 |
---|---|
[JavaScript] JSON (JavaScript Object Notation) (2) | 2020.09.17 |
[React] prop-types (0) | 2020.09.02 |
[JavaScript] Object Destructuring (0) | 2020.09.02 |
[JavaScript] Array Destructuring (0) | 2020.09.02 |
댓글