Skip to content

Instantly share code, notes, and snippets.

@Charpell
Created September 3, 2020 09:17
Show Gist options
  • Save Charpell/4bf1d9d943b4f885f7e92bd747895bca to your computer and use it in GitHub Desktop.
Save Charpell/4bf1d9d943b4f885f7e92bd747895bca to your computer and use it in GitHub Desktop.
Test
//To prevent re-render, we are going to use React.memo() which is an memoization technique. It’s primarily used to speed up computing by story the result of a function and returning the cached result, when the same inputs occur again
//The onNameClick function will be wrapped with React.memo()
import * as React from "react";
const ALL_NAMES = ["foo", "bar", "baz"];
interface NameListItemProps {
readonly name: string;
readonly onNameClick: (clickedName: string) => void;
}
const NameListItem: React.FC<NameListItemProps> = (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.memo((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>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment