score:9

Accepted answer

This is the correct way of doing it. There are two ways of condensing this if needed.

First is to just pass a tuple instead of two separate props.

const Container: React.FC = () => {
  const [num, setNum] = useState(0);
  return <Counter numState={[num, setNum]} />
};

interface CounterProps {
  numState: [number, React.Dispatch<React.SetStateAction<number>>];
}

const Counter: React.FC<CounterProps> = ({ numState: [num, setNum] }) => {
  const handleClick = () => {
    setNum(num + 1);
  };
};

or do it more cleanly by passing an object with the keys 'state' and 'setter' or something similar.

Secondly, if you find that you're using this sort of thing a lot, then you might want to invest some time into setting up a global state management system like Redux.


Related Query

More Query from same tag