React의 State React State Management
State? Props?
- Props are passed from parent components to child components, allowing child components to display those values
- Since props are values passed from parent to child components, the values cannot be changed inside the component where props are actually used
- State refers to values that can be changed “inside” a React component
State in Class Components
To use State, declare it inside the class as follows:
constructor(props) {
super(props);
this.state = {
number: 0,
};
}
How It’s Actually Used
import React, { Component } from "react";
export default class TestStateClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
number: 0,
};
}
render() {
const { number } = this.state;
return (
<div>
<h4>{number}</h4>
<button
onClick={() => {
this.setState({ number: number + 1 });
}}
>
+1
</button>
</div>
);
}
}
State in Functional Components
To use state in functional components, do the following:
import React, { useState } from "react";
const [message, setMessage] = useState();
How It’s Actually Used
import React, { useState } from "react";
export default function TestFuncComponent() {
const [message, setMessage] = useState();
const onClickEnter = () => setMessage("Hello!");
const onClickLeave = () => setMessage("Goodbye!");
return (
<div>
<h3>{message}</h3>
<button onClick={onClickEnter}>Enter</button>
<button onClick={onClickLeave}>Leave</button>
</div>
);
}
You can also set a default value for state:
const [message = "This is React", setMessage] = useState();
댓글남기기