Single-function alternative for React.useState

Gunar Gessner

Gunar Gessner

Jul 21, 2020

function useSt8(initial) {
  return st8.bind(useState(initial));

  function st8() {
    switch (arguments.length) {
      case 0:
        return this[0];
      case 1:
        return void this[1](arguments[0]);
        throw new Error("Expected 0 or 1 arguments");

Originally seen here, but posted here as a snippet because it's small enough to just copy and paste instead of growing the dependency tree.

Sign up for the newsletter

Read other stuff