DEV Community

Discussion on: Converting a React component to TypeScript

mbarzeev profile image
Matti Bar-Zeev Author

... and another thing - I like to keep my component's state as such, even though the "disabled" can be calculated on render. I find it more convenient if later on I would like to introduce a prop which initialize that state and it is much more readable IMO.

Thread Thread
lukeshiru profile image

If you introduce a new prop, that prop can be added to the logic of disabled. If you want to keep it readable you can have it in a const instead of having it inline. What's important is to avoid using state when you don't need it, and in this case disabled can be inferred from other state+props, so no need for a state for it and a reducer just to keep that in sync. I mean you have:

// This
const Example = ({ logic }) => {
    const [disable, setDisable] = useState(true);
    useEffect(() => setDisable(logic), [logic]);
    return <input disabled={disable} />;

// vs this:
const Example = ({ logic }) => {
    return <input disabled={logic} />;
Enter fullscreen mode Exit fullscreen mode