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?

【React】useCallbackについて

Posted at

useCallbackの引数は依存配列に関係ない

import { useCallback, useState } from "react";

const Index = () => {
  const [name, setName] = useState<string>("");

  // 引数valの値をconsole.logで出力
  // 依存配列は[]
  const handleClick = useCallback((val: string) => {
    console.log("callback " + val);
  }, []);

  return (
    <div className="w-screen h-screen bg-red-50">
      <div className="w-full h-full flex justify-center items-center">
        <div className="w-1/2 h-1/2 bg-slate-200">
          <div className="w-full h-full flex justify-center items-center">
            
            <button
              onClick={() => handleClick(name)}
              className="p-2 rounded-sm bg-indigo-400 text-white shadow-md"
            >
              Click me
            </button>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.currentTarget.value)}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Index;

image.png

  • 依存配列が[]となっていても、引数の値が変わればちゃんと出力される
  • useCallback関数を渡した子要素も、再レンダリングされない
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?