ReactTypeScript

IDEA: componentWillUnmount をHookで作る

componentWillUnmount を使うことでReduxステートのリセットなどができます。 が、React Hookを使う場合はこれに該当するAPIが存在しません。 IDEA:useComponentWillUn […]

広告ここから
広告ここまで

componentWillUnmount を使うことでReduxステートのリセットなどができます。

class AnyComponent extends React.Component {
  componentWillUnmount() {
    this.props.resetTheTitle()
  }
  render() {
    return <h1>{this.props.title}</h1>
  }
}

が、React Hookを使う場合はこれに該当するAPIが存在しません。

IDEA:useComponentWillUnmount hookを作る

ということで今のところ代替手段として使っているのがこのコードです。

import { useEffect, useCallback } from "react"

export const useComponentWillUnmount = (callback: Function, ...args: any[]) => {
    const cb = useCallback(() => {
        callback(...args)
    }, [callback, args])
    return useEffect(() => {
        return () => {
            cb()
        }
    }, [])
}

使い方はこちら。

import { useComponentWIllUnmount } from './path/to/the/file';

type Props = {
  title: string,
  resetTheTitle: (postId: string) => void,
  postId: string
}
export default ({title, resetTheTitle, postId}: Props) => {
  useComponentWillUnmount(resetTheTitle, postId);
  return <h1>{title}</h1>;
}

複数の引数を受け入れられるようになっているので、このような使い方もできます。

import { useComponentWIllUnmount } from './path/to/the/file';

type Tag = {
  Name: string;
  Value: string;
}
type Props = {
  title: string;
  resetTheTitle: (postId: string) => void;
  postId: number;
  author: string;
  tag: Tag
}

export default ({title, resetTheTitle, postId, author, tag}: Props) => {
  useComponentWillUnmount(resetTheTitle, postId, author, tag);
  return <h1>{title}</h1>;
}

個人的にはそんなややこしいのはuseCallbackでまとめてから渡してくれとも思わないでもないですが、、、

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts