Skip to content

Instantly share code, notes, and snippets.

@tennox
Last active December 9, 2021 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tennox/3b25845d2bf9c5204638fd18e3595d50 to your computer and use it in GitHub Desktop.
Save tennox/3b25845d2bf9c5204638fd18e3595d50 to your computer and use it in GitHub Desktop.
React: Pass useState hook to child
import React, { FC, useState } from 'react';
const Component = () => {
const [barFoo, setBarFoo] = useState(1);
return <Foo bar={[barFoo, setBarFoo]} />;
};
const Foo: FC<{ bar: StateRef<number> }> = ({ ...state }) => {
const [bar, setBar] = state.bar;
return <div />;
};

Why?

  • I often pass state to child component (best practice I found)
  • keep scope-dependent naming
  • decrease boilerplate
  • correct types

Disadvantages I found:

  • doesn't report unused state (because of ...state) - fixed when doing it like this:
    const Foo: FC<{ bar: StateRef<number> }> = ({ bar: barState }) => {
      const [bar, setBar] = barState;
      return <div />;
    };
import { useState, Dispatch, SetStateAction } from 'react';
// wrapper for the return type of useState https://stackoverflow.com/a/64840774/1633985
interface wrappedUseState<S> {
(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
}
/** example: const [a, setA]: StateRef<string> = useState<string>() */
export type StateRef<T> = ReturnType<wrappedUseState<T>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment