Extract Generic React Hook Code into Custom React Hooks

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

Because hooks code is regular JavaScript, extracting it to its own function is trivial and enables code sharing in a really nice way. It also allows us to encapsulate and separate concerns really cleanly. Custom hooks also compose really nicely together to build more complex hooks out of more primitive ones. Let's do this by creating a useSetState and useSafeSetState custom hook.

If you would like a more comprehensive useSetState hook, give use-legacy-state a try.

Rob Eberhardt
Rob Eberhardt
~ a year ago

I'm receiving a "Hooks can only be called inside the body of a function component." warning after making the changes in this video.

It looks like the treatment of useSafeSetState inside the useEffect differs in this Video and the Git repo.

Kent C. Dodds
Kent C. Doddsinstructor
~ a year ago

I'm not sure what you're looking at. Here's what I see when I click the GitHub button above and navigate to this file: https://github.com/kentcdodds/react-github-profile/blob/1bbf5d9ff69197ac4f03a4612348bc2b5247b957/src/screens/user/components/query.js#L13-L24