useState Hook

When in doubt, TypeScript is going to try its hardest to infer types on your behalf. Let's look at the following silly update to our component.

const Question = ({ question, answer }: QuestionProps) => {
  return (
    <article className="question">
      <header>{question}</header>
      <p className="answer">
        <span className="blurred">{answer}</span>
      </p>
      <footer>
        <button>Toggle Answer</button>
      </footer>
    </article>
  );
};

The notable and new piece is our use of React's useState hook.

const [isHidden, toggleHidden] = React.useState(false);
  • isHidden is defined as false from the get-go, which means TypeScript can assume it's supposed to be a boolean.
  • toggleHidden infers that, since isHidden is supposed to be a boolean, that it should take a boolean as an argument.

The inferred types are as follows:

const isHidden: boolean;
const toggleHidden: React.Dispatch<React.SetStateAction<boolean>>;

That second type for toggleHidden is a bit stranger than anything we've seen before, but we'll talk more about that later.

This will work any time that we have a default value for a piece of state.

const [name, setName] = useState("Steve");

It looks like it was a string. So, we must be ready to go.

const name: string;
const setName: React.Dispatch<React.SetStateAction<string>>;

We need to do a little more work to make this application worth using.

const Question = ({ question, answer }: QuestionProps) => {
  const [hidden, toggleHidden] = useState(true);

  return (
    <article className="question">
      <header>{question}</header>
      <p className="answer">
        <span className="blurred">{answer}</span> /* ✅ */
        <span className={`${hidden ? "blurred" : "visible"}`}>{answer}</span>
      </p>
      <footer>
        <button>Toggle Answer</button>
        <button onClick={() => toggleHidden(!hidden) /* ✅ */}>
          Toggle Answer
        </button>
      </footer>
    </article>
  );
};

Where Are We Now?

This sandbox represents where we are at the end of this section.

  • examples/07-avengers-quiz-with-use-state
  • projects/avengers-quiz on the avengers-quiz-with-use-state branch