1
3

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 5 years have passed since last update.

ReactNativeでhooksを利用する最低限過ぎるメモ。

Last updated at Posted at 2019-11-14

React 16.8から導入されたHook。
関数コンポートにおいて、state管理やcomponentDidMount等と同等の機能を利用するためのもの。
代表的なものはstate hooksとeffect hooks。

ステートフック

ステートを管理するためのもので下記の構文で利用できる。

const [変数,関数] = useState(初期値);

副作用(effect)フック

componentDidMount()等と同等の機能を提供する。下記のような構文で利用する。
どういう動きをするかは引数で決まる(制御できる)。

componetDidMount風

下記のように書くと1回だけ実行。

useEffect(()=>{},[]);

変化があるか

countが変化してるいるかどうか。

useEffect(()=>{},[count]);

サンプル

とりあえず。

App.js
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {

  //state hook
  const [count, setCount] = useState(0);

  //effect hook
  useEffect(() => {
    console.log('you clicked ' + count + 'times');
  });

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>You clicked {count} times.</Text>
      <Button
        title="click me"
        onPress={() => setCount(count + 1)}
      />
    </View>
  );
}
1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?