1
0

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 使ってみた

Posted at

useStateを実際に使おう

useStateとは?

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

(react 公式サイトuseStateより引用)

React公式サイトにはこのように書いています。

ん?わからない。

なので実際に簡単なコードを書いてみました。

※これはReact Application上で書きました

コード1

const example = useState(0)
console.log({example})

この場合のconsole.logの出力は次のようになります。

example: Array(2)

これの中身を見るとこのようになっています。

0: 0
1: f()

つまりexampleは配列になっています。
1番目には初期値である0が
2番目には関数が入ります。

コード2

useState()の括弧の中が
本当に初期値なのかと疑問に思ったので
console.logしてみました。

const example = useState(500)
console.log({example})

この場合のexampleの配列の中身は次のようになります。

0: 500
1: f()

ちゃんと初期値になってます!

コード3

この配列には2つの要素が入ることがわかりました。
ここでjavascriptの分割代入を使って
それぞれの要素を受け取るようにします。

const [count, setCount] = useState(0);
const up =() => setCount(count +1)

ここでupはcountを+1します。
countの状態を変えるために
setCountをこのように使います。
これによりcountの値を+1していくことができます。

実際に書いたコード

import react, {useState} from 'react';
const App = () => {
const [count, setCount] = useState(0);
const up =() => setCount(count +1)
const down =() => setCount(count -1)
return (
<>
<div>count: {count}</div>
<div>
<button onClick={up}>+1</button>
<button onClick={down}>-1</button>
</div>
</>
);
}

export default App;

学習したことを応用して
簡単なカウンターを作ってみました。

buttonタグでボタンを表示し
onClickはボタンを押したときの処理です。
こうすることでボタンを押して
+1,-1できるカウンターの出来上がりです!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?