Skip to content

#03.1: Compound components (with callback) #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions showcase/src/patterns/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, {
useEffect,
useContext,
useMemo,
useRef,
createContext
} from 'react'

Expand Down Expand Up @@ -117,7 +118,7 @@ const initialState = {
const MediumClapContext = createContext()
const { Provider } = MediumClapContext

const MediumClap = ({ children }) => {
const MediumClap = ({ children, onClap }) => {
const MAXIMUM_USER_CLAP = 50
const [clapState, setClapState] = useState(initialState)
const { count, countTotal, isClicked } = clapState
Expand All @@ -134,6 +135,18 @@ const MediumClap = ({ children }) => {
})
}

const componentJustMounted = useRef(true)

useEffect(
() => {
if (!componentJustMounted.current) {
onClap(clapState)
}
componentJustMounted.current = false
},
[count, onClap]
)

const memoizedValue = useMemo(
() => ({
count,
Expand Down Expand Up @@ -190,11 +203,11 @@ const CountTotal = () => {
)
}

const ClapInfo = () => {
const ClapInfo = ({ info }) => {
const { countTotal } = useContext(MediumClapContext)
return (
<div className={styles.info}>
{wordConverter.toWords(countTotal)} claps!
{info || wordConverter.toWords(countTotal)} claps!
</div>
)
}
Expand All @@ -211,12 +224,18 @@ MediumClap.Info = ClapInfo
==================================== **/

const Usage = () => {
const [total, setTotal] = useState(0)

const onClap = ({ countTotal }) => {
setTotal(countTotal)
}

return (
<MediumClap>
<MediumClap onClap={onClap}>
<MediumClap.Icon />
<MediumClap.Total />
<MediumClap.Count />
<MediumClap.Info />
<MediumClap.Info info={`Your article has been clapped ${total} times`} />
</MediumClap>
)
}
Expand Down