25 ms·
Also, you can get compile-time strict typing in Typescript with some minor annotations added to that: export const Counter: FunctionComponent<{ lab
by crooked-v 6y ago
Also, you can get compile-time strict typing in Typescript with some minor annotations added to that:
export const Counter: FunctionComponent<{
label: string;
counterType: 'Increment' | 'Decrement';
onClick: () => void
}> = ({ label, counterType, onClick }) => {
const [counter, setCounter] = useState<number>(0);
return (
<button onClick={() => {
counterType == "Increment" && setCounter(counter + 1);
counterType == "Decrement" && setCounter(counter - 1);
onClick && onClick();
}}>
{label}: {counter}
</button>
);
}
- chvid 6y agoYes. You can add types if you want. And maybe one can discuss if there is a more elegant syntax than the C-style syntax of JavaScript (there is ...). Other than that. I think the code is about as concise as it gets.
- ddek 6y agoThere is a change I’d make though - I’d memo-ise the click handler with useCallback. By using the function ‘overload’ on setState, which is guaranteed not to change, the callback will only be calculated (?) when the onclick handler changes. The setState would look like this: setState(c => c + 1);. Right now, the callback is interpreted on every render cycle.