10
7

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集1 (useBooleanState)

Last updated at Posted at 2019-08-09

おすすめ自作 React hooks集1

公式ドキュメントへのリンク

useBooleanState

ダイアログの開閉状態などのbooleanのstateを書くのに、毎回無駄に長い同様の処理を書いていたのでまとめたもの。
超簡単だけどあると便利。

import { useState, useCallback } from 'react';

export const useBooleanState = (
  init: boolean
): [boolean, () => void, () => void] => {
  const [state, setState] = useState<boolean>(init);

  const setTrue = useCallback(() => {
    setState(true);
  }, []);

  const setFalse = useCallback(() => {
    setState(false);
  }, []);

  return [state, setTrue, setFalse];
}

使用例

import { Dialog } from "somewhere";

export const MyComponent = () => {
  const [dialogIsOpen, open, close] = useBooleanState(false);

  return (
    <div>
      <Dialog open={dialogIsOpen} onClose={close} />
      <button onClick={open}>Open Dialog!</button>
    </div>
  )
}

使用前

import { Dialog } from "somewhere";

export const MyComponent = () => {
  const [dialogIsOpen, setDialogIsOpen] = useState<boolean>(false);
  
  const open = useCallback(() => {
    setDialogIsOpen(true);
  }, []);

  const close = useCallback(() => {
    setDialogIsOpen(false);
  }, []);

  return (
    <div>
      <Dialog open={dialogIsOpen} onClose={close} />
      <button onClick={open}>Open Dialog!</button>
    </div>
  )
}

おすすめ自作 React hooks集は随時追加予定です。

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?