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

    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>;
    };
    
    Published on February 19th, 2021 in Technical, TypeScript, React

    Did you enjoy this article?

    Continue reading about A TypeScript trick for reusable 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 ❤️