0
0

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.

【React練習問題】(回答)②カスタムhooksをつかって表示制御をしよう

Posted at

課題の目的

カスタムhooksの基礎的な使い方を理解してもらいたかった。

回答

実装方法はそれぞれ違うと思うので、一つの例だと思って見てほしいです。

import React, { useState, useCallback, memo} from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  const [isOpen, open, close] = useOpenComment();
  const [isOpen2, open2, close2] = useOpenComment();
  return (
    <div>
      <button onClick={open}>open!!</button>
      <button onClick={open2}>open2!!</button>
      <Comment isOpen={isOpen} close={close} comment="openしました!"/>
      <Comment isOpen={isOpen2} close={close2} comment="openしました!2"/>
    </div>
  );
};

const useOpenComment = () => {
  const [isOpen, setIsOpen] = useState(false);
  const open = useCallback(() => setIsOpen(true), []);
  const close = useCallback(() => setIsOpen(false), []);
  return [isOpen, open, close];
};

const Comment = memo(({isOpen, close, comment}) => (
  <>
  {isOpen ?  
    <div className="comment">
      <p>{comment}</p>
      <button onClick={close}>close</button>
    </div>
    : null
  }
  </>
));

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

仕様の実装

・useStateを1回だけ使う
・useCallbackを2回だけ使う
これをカスタムhooksをつかって解決している。

const useOpenComment = () => {
  const [isOpen, setIsOpen] = useState(false);
  const open = useCallback(() => setIsOpen(true), []);
  const close = useCallback(() => setIsOpen(false), []);
  return [isOpen, open, close];
};

これをつくっておくことで、ボタンで利用する関数を毎回定義しなくても、useOpenCommentを呼び出すだけで必要な関数を呼び出すことだできるようになる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?