0
1

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.

Render PropsとHooksで処理中を管理する

Last updated at Posted at 2020-03-27

Render PropsとHooksでローディング処理を管理する

ローディングや処理中を管理する方法として useState を使うことは多いと思います。
しかし複数のフォームやコンポーネントが処理中である・・・等管理したい場合に useState だけではの管理では気持ち悪かったので、それの対策っぽい記事を書きます

こんなかんじ

LoadingProvider.tsx

import React, {useState, FC, ReactElement} from 'react';

type RenderProps = {
  loading: boolean
  setLoading: (bool: boolean) => void
}

type Props = {
  initialValue?: RenderProps['loading']
  children: (props: RenderProps) => ReactElement
}

export const LoadingProvider: FC<Props> = ({children, initialValue = false}) => {
  const [loading, setLoading] = useState(initialValue);

  return children({loading, setLoading})
};

ProductPage.tsx

export const ProductPage: FC<> = ({ products actions }) => {
 return (
    {products.map(product => (
       <LoadingProvider>
        {({loading, setLoading}) => {
            <Product
              product={product}
              addToCart={async () => {
                setLoading(true)
                actions.addToCart(product.id)
                setLoading(false)
              }
                // 処理中のprops
                processing={loading}
             />
          }}
         </LoadingProvider>
    ))}
 )
} 

以上!
これなら複数のComponetが処理中でも脳死で使えるきがする。

最初はContextAPIを使おうと思ったが、今回のケースだとこれくらいの実装が最適かなと。
LoadinProviderで loading === true だったら、Loadingのグルグルを表示させるComponentに差し替える。みたいなのを実装するのもよさそう。

むやみにRenderPropsを使うのは微妙そうだけど、こういうケースでは有用だなーとおもいました。 まる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?