Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Custom react hooks ❤️

    This is a story full of wonderful new possibilities, beautiful codey things, and components clean as the mountain air. All thanks to custom react hooks ❤️

    While livecoding on the ThreadCompiler project yesterday, I noticed that with hooks our logic was getting tied up with presentation. All state was local, all logic inside components, shared state was weird, and our components looked like crap.


    Here's an example.

    A component that takes user input from React Context using Constate, passes it through a Remark compiler, then puts the result back in context (so other components can use it), and renders the result locally.

    Local result for user preview, context for TweetButton so we can send it into the world.

    techletter app screenshot 1549905697157

    What a mess 🤮

    We have a rendered state and its setter, then a useEffect that runs on value changes. Passes value through Remark with custom plugins and gets the result.

    Result goes into local state via setRendered, triggering a re-render showing a user preview. Result also goes into context with setOutput which triggers a re-render in <TweetButton> making it ready to tweet things out. ugh

    TweetButton is even worse …

    techletter app screenshot 1549905819350

    We have 3 local states for success, error, and API result. A whole API call function, and some rendering. All inside this poor little component that's supposed to be a button.

    Oy vey 🙄

    How to fix your mess with a custom hook

    We can clean this up with custom hooks.

    Custom hooks are functions built on top of basic React Hooks. You can build them anywhere in your project, use them in a component, and it just works. 👌

    Starting with the <Tweet> component, we can take out all that logic and wrap it in a new function.

    techletter app screenshot 1549905842949

    It's customary to prefix your hooks with use. I like to put them in a directory.

    We now have a useRemark hook with local state and an effect. When input changes it runs through renderTweet. The promise result goes into state. We return the current rendered state.

    Extracting the Remark stuff itself into a renderTweet method makes it easier to use in <TweetButton>. You'll see.

    This new custom hook makes <Tweet> the sweet little component it was always meant to be.

    techletter app screenshot 1549905865408

    Beautiful ❤️

    Something similar happens when we extract the <TweetButton> mess into a hook. Check this out 👇

    Custom hook

    techletter app screenshot 1549905887363

    Almost same code as before.

    You've got your 3 local states, and your sendTweets function. Moved the actual API call to a separate sendTweet function to clean up some more.

    Upon success we update the array of tweet responses, update error and success states, etc.

    The hook returns an object with everything your component needs to use it. List of tweets, current error, the success state, and a sendTweets method.

    Your button component now looks like a button ❤️

    techletter app screenshot 1549905908783

    Much clearer 👌

    So how'd we do it?

    Nothing special. You might even say "Wait that's it?"

    You take your hooky mess, wrap it in a new method, call it useSomething, and voila: that method is a React hook and you've just created a custom hook. Congratz 👏

    Enjoy your week

    Cheers, ~Swizec

    PS: I discovered the floppotron this morning. It is amazing

    Published on February 11th, 2019 in Front End, Technical

    Did you enjoy this article?

    Continue reading about Custom react hooks ❤️

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️