0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React Hooksをおさらい - UseState

Last updated at Posted at 2020-03-11

UserState

classのstateの代用関数でfunction component内でもstateを持たせる事が可能になった(react 16.8より)
https://reactjs.org/docs/hooks-intro.html

使用例

const [currentCount, setCount] = useState({count: 0}); 

const onClickHandler = () => {
    setCount({count: currentCount + 1 })
}

useStateは複数回使っても良い

複数回使っても良い事を踏まえると、同時にアップデートしないStateに関しては別けると読みやすい。

// 例えば以下のClass Componentを

state = {
  count: 0, 
  name: 'kondo',
}

onClickIncrementHandler() => {
 this.setState({count : count + 1});
}

onChangeNameHandler() => {
  this.setState({name : 'honda'});
}

// function componentに変えると以下の様にも書き換えれるが

[currentState, setState] = useState({
  count: 0, 
  name: 'kondo',
})

const onClickIncrementHandler = () => {
 setState({...currentState, count : count + 1});
}

const onChangeNameHandler = () => {
  setState({...currentState, name : 'honda'});
}

// 以下の方が各関数がそれぞれの役割りが分かりやす

[currentCount, setCount] = useState(0);
[currentName, setName] = useState('kondo')

const onClickIncrementHandler = () => {
 setCount(currentCount + 1);
}

const onChangeNameHandler = () => {
  setName('honda');
}

良かったらJSBinで遊んで見てください。
https://jsbin.com/puriregedi/3/edit?js,output

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?