How do I change props from a child component using hooks?
Asked Answered
H

2

8

I'd like to change the props using react hooks, and I found the way passing setState function as props to the child.

Container.tsx

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

};

Counter.tsx

interface CounterProps {
  num: number;
  setNum: React.Dispatch<React.SetStateAction<number>>;
}

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

  return (
    // jsx codes...
  );
};

It works well, but I have to add two props to the child component per one state of the parent. Is there a more efficient way for this problem?

Harryharsh answered 10/12, 2019 at 6:48 Comment(1)
I think there is no problem using two props like that. This looks clear.Uranic
K
9

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.

Koerner answered 10/12, 2019 at 7:27 Comment(1)
I think you can make it even shorter: numState: [number, React.Dispatch<number>]Lipread
P
1

This can be simplified even further now, since TypeScript 2.8 added ReturnType, by obtaining the return type of the useState hook.

interface CounterProps {
    numState: ReturnType<typeof useState<number>>
}

const Counter = ({ numState: [num, setNum] }: CounterProps) => {
    const handleClick = () => {
        setNum(num + 1)
    }
}
Pursuant answered 20/7, 2023 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.