Open4
React Hooks
useBool
概要
Boolean を管理するための Hooks。
定義
import { useState } from 'react'
export const useBool = (initialValue: boolean): [boolean, () => void, () => void] => {
const [value, setValue] = useState(initialValue)
return [value, () => { setValue(true) }, () => { setValue(false) }]
}
使い方
const [showModal, openModal, closeModal] = useBool(false)
useMount
概要
コンポーネントのマウント時に実行する Hooks。
定義
import { useEffect } from 'react'
export const useMount = (callback: () => void): void => {
useEffect(callback, []) // eslint-disable-line react-hooks/exhaustive-deps
}
使い方
useMount(() => {
fetchAPI('/hoge')
})
useUnmount
概要
コンポーネントのアンマウント時に実行する Hooks。
定義
import { useEffect } from 'react'
export const useUnmount = (callback: () => void): void => {
useEffect(() => callback, []) // eslint-disable-line react-hooks/exhaustive-deps
}
使い方
useUnmount(() => {
clearItem()
})
useModal
概要
モーダルを使うための Hooks。
定義
-
useBool
が必要
import { type ReactNode } from 'react'
import { useBool } from '@/hooks/useBool'
export const useModal = (initialState: boolean = false): [({ children }: { children: ReactNode }) => ReactNode, () => void, () => void] => {
const [isOpen, openModal, closeModal] = useBool(initialState)
const modal = ({ children }: { children: ReactNode }): ReactNode => (
<dialog open={isOpen}>
{children}
</dialog>
)
return [modal, openModal, closeModal]
}
使い方
const [Modal, openModal, closeModal] = useModal()
return (
<Modal>
<p>Hello.</p>
<button onClick={closeModal}>Close</button>
</Modal>
)