Swizec Teller - a geek with a hatswizec.com

    A TypeScript trick for reusable hooks

    How do you write a reusable React hook?

    Oh that's easy, every hook is reusable! ๐Ÿฅณ

    function useMyLittleStateMachine() {
    const [state, setState] = useState("start");
    let nextState = state;
    switch (state) {
    case "start":
    nextState = "second";
    break;
    case "second":
    nextState = "third";
    break;
    case "third":
    nextState = "start";
    break;
    }
    return { state, nextState };
    }

    You get a tiny little state machine that doesn't do much. Runs you 'round in a circle.

    A tiny 3-state state machine
    A tiny 3-state state machine

    Let's pretend you're using it for routing because that's what I was building to get this idea. "What is the next step in this UX flow?"

    You use the state machine like this:

    const GoNext = () => {
    const { nextState } = useMyLittleStateMachine();
    return <Link to={`/important_flow/{nextState}`}>Go Next</Link>;
    };

    Handy way to decouple sequences of UI views. You think it's silly until your PM starts shuffling things around to run A/B tests.

    A linear state machine is silly

    You wouldn't bother with a linear state machine. Make it an array, use incrementing index. Way easier.

    But UX flows like to depend on context.

    function useMyRoutingStateMachine(user: User) {
    // from React Router, returns current location
    const location = useLocation();
    let nextRoute = "start";
    switch (location.path) {
    case "start":
    if (user.valid) {
    nextState = "do_things";
    } else if (user.badName) {
    nextState = "fix_name";
    } else {
    nextState = "error";
    }
    break;
    case "fix_name":
    if (user.valid) {
    nextState = "do_things";
    }
    // ...
    }
    return { nextState };
    }

    Each state checks properties on the user model to decide what comes next. An error, a data-fixing form, the core functionality, ...

    This is great. Put it anywhere in your app, give current user, and it says what screen comes next. ๐Ÿฅณ

    A non-reusable state machine, phooey

    You've got this cool little state machine that works for users.

    What about for comments? Those are similar if you squint hard enough. The flow starts, then you can have an error, fix things ... hmmmm ๐Ÿค”

    Yes I know I'm stretching. It's an example to show a thing.

    If comments and users share the important properties, you can do this:

    function useMyRoutingStateMachine(context: User | Comment) {
    // from React Router, returns current location
    const location = useLocation();
    let nextRoute = "start";
    switch (location.path) {
    case "start":
    if (context.valid) {
    nextState = "do_things";
    } else if (context.badContent) {
    nextState = "fix_content";
    } else {
    nextState = "error";
    }
    break;
    case "fix_content":
    if (context.valid) {
    nextState = "do_things";
    }
    // ...
    }
    return { nextState };
    }

    A union type says the context param should be either a User or a Comment. You read it like an OR, but it's not an OR.

    Union means the new type has all the shared properties.

    And that's where things blow up. The more you lean into union types, the harder TypeScript has to work, the more you'll see errors like this:

    types of parameters 'user' and 'context' are incompatible
    Type 'User | Comment' is not assignable to type 'Comment'
    Type 'User' is missing the following properties from type 'Comment'

    ๐Ÿ’ฉ

    TypeScript generics to the rescue

    When you're done pulling your hair out, here's what you do ๐Ÿ‘‰ you sprinkle a TypeScript generic on your code. They're not as scary as they look.

    function useMyRoutingStateMachine<T>(context: T) {
    // ...
    }

    Context is of generic type T as specified when the hook is used.

    const GoNextUser = (user: User) => {
    const { nextState } = useMyLittleStateMachine<User>(user);
    return <Link to={`/important_flow/{nextState}`}>Go Next</Link>;
    };
    const GoNextComment = (comment: Comment) => {
    const { nextState } = useMyLittleStateMachine<Comment>(comment);
    return <Link to={`/important_flow/{nextState}`}>Go Next</Link>;
    };

    Call the hook and tell it the type of its parameter. You've done this before with library hooks, at least useState, but it feels special when it's your own.

    You can go even further. Make the component generic.

    const GoNext = (context: T) => {
    const { nextState } = useMyLittleStateMachine<T>(context);
    return <Link to={`/important_flow/{nextState}`}>Go Next</Link>;
    };

    ๐Ÿคฏ

    TypeScript doesn't care about the name of the type you're passing around. As long as its consistent.

    Obvious in retrospect.

    Cheers,
    ~Swizec

    PS: you can use generics in type definitions and that blows my mind

    export type FlowMachine<T> = {
    // init step is required
    init: FlowStep<T>;
    [key: string]: FlowStep<T>;
    };
    type FlowStep<T> = {
    path: string;
    nextStep: (context: T) => FlowStep<T>;
    };

    Did you enjoy this article?

    Published on February 19th, 2021 in Technical, TypeScript, React

    Learned something new?
    Want to become a high value JavaScript expert?

    Here's how it works ๐Ÿ‘‡

    Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet ๐Ÿ“–right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Start with an interactive cheatsheet ๐Ÿ“–

    Then get thoughtful letters ๐Ÿ’Œ on mindsets, tactics, and technical skills for your career.

    "Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. ๐Ÿ‘Œ"

    ~ Ashish Kumar

    Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. โœŒ๏ธ

    Have a burning question that you think I can answer?ย I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

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

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first ๐Ÿ’ฐ on the side with ServerlessReact.Dev

    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 bySwizecwith โค๏ธ