Last active
November 16, 2020 03:36
-
-
Save kleavjames/be1bc857cfdc0e5c5f33e4dd25ca7edc to your computer and use it in GitHub Desktop.
pool-office-manager-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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 addeduseCallback
hook in the onNameClick function with empty array.