Created
September 3, 2020 09:17
-
-
Save Charpell/4bf1d9d943b4f885f7e92bd747895bca to your computer and use it in GitHub Desktop.
Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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