LoginSignup
0
1

More than 3 years have passed since last update.

React hook 一覧①

Posted at

Reactのフックについて説明していきます。

Hookとは接続という意味です。

①useState
更新の時に使う。
例えば、ボタンを押す度に数字が+1になるときなどは、
ボタンを押すたびに更新をしなきゃなりません。
このような更新をする時に使います。

const [state, setState] = useState()

②useEffect
第二引数の依存している値が変更される度に第一引数が実行される。
この他にも使い方はありますが今回は理解できるように細かい使い方は割愛しています。

const hookFunction = () => {

  const [count, setCount] = useState(0)

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

return(
    <div>
       <p>{count}</p>
       <button onClick={() => setCount(count + 1)}>プラス1する</button>
    </div>
);
}

③useContext
これを使うにはまずは下記のように入力する必要があります。

export const UserCount = React.createContext()

これを親コンポーネントで使用したら、valueをいれることができて、そのvalueを子のコンポーネントでも使えるようになります。

const value = useContext(MyContext);

下記の記事が非常にわかりやすいです

④useReducer
useStateの代替品です。
useStateを使う時はシンプルなロジックで更新をしたいときに使います。
useReducerはロジックが複数あり複雑だったり、複数のロジックを分かり易くしたいときに使います。ボタンを押したら初期値に戻るなどのアクションをするときも便利です。
公式サイトがわかりやすいです。

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