Skip to content

Instantly share code, notes, and snippets.

@kleavjames
Last active November 16, 2020 03:36
Show Gist options
  • Save kleavjames/be1bc857cfdc0e5c5f33e4dd25ca7edc to your computer and use it in GitHub Desktop.
Save kleavjames/be1bc857cfdc0e5c5f33e4dd25ca7edc to your computer and use it in GitHub Desktop.
pool-office-manager-test
import React from "react";
const ALL_NAMES = ["foo", "bar", "baz"];
interface NameListItemProps {
readonly name: string;
readonly onNameClick: (clickedName: string) => void;
}
const NameListItem: React.FC<NameListItemProps> = React.memo(
(props: NameListItemProps) => (
<li>
<button onClick={() => props.onNameClick(props.name)}>
{props.name}
</button>
</li>
)
);
const NameList: React.FC = () => {
const [lastClickedName, setLastClickedName] = React.useState<
string | undefined
>(undefined);
const onNameClick = React.useCallback(
(clickedName: string) => setLastClickedName(clickedName),
[]
);
return (
<div>
<h1>
{lastClickedName === undefined
? "No Name Clicked Yet"
: lastClickedName}
</h1>
<ul>
{ALL_NAMES.map((name: string, idx: number) => (
<NameListItem key={idx} name={name} onNameClick={onNameClick} />
))}
</ul>
</div>
);
};
export default NameList;
@kleavjames
Copy link
Author

In the given code, what I did is wrap the child component NameListItem with React.memo. It will only render once, it still receives the same props. I also added useCallback hook in the onNameClick function with empty array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment