Skip to content

Instantly share code, notes, and snippets.

@revanth0212
Last active August 31, 2019 16:59
Show Gist options
  • Save revanth0212/1a4c949a70a98aae3cb7f0ed5775692c to your computer and use it in GitHub Desktop.
Save revanth0212/1a4c949a70a98aae3cb7f0ed5775692c to your computer and use it in GitHub Desktop.
A sample Hooks component demonstrating Life Cycle Methods Composition.
function useLikes() {
const [likes, setLikes] = useState(0)
const [likedByMySelf, setLikedByMySelf] = useState(false)
useEffect(() => {
fetchLikes().then(({ likes, likedByMySelf }) => {
setLikes(likes)
setLikedByMySelf(likedByMySelf)
})
}, [])
const onLike = () => {
setLikes(likedByMySelf ? likes - 1 : likes + 1)
setLikedByMySelf(!likedByMySelf)
}
return [likes, likedByMySelf, onLike]
}
function useComments() {
const [comments, setComments] = useState([])
useEffect(() => {
fetchComments().then(setComments)
}, [])
const onComment = comment => {
setComments([...comments, comment])
}
return [comments, onComment]
}
function Feed() {
const [likes, likedByMySelf, onLike] = useLikes()
const [comments, onComment] = useComments()
return (
<RenderTheComponent
likes={likes}
likedByMySelf={likedByMySelf}
comments={comments}
onComment={onComment}
onLike={onLike}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment