what is the best approach?
i need a boolean to use in a button and the result of this boolean i already have in a state of menuPosition.
const [menuPosition, setMenuPosition] = useState<null | HTMLElement>(null);
I thought creating a new state:
const [open, setOpen} = useState<Boolean>(false)
but, i could also derivate from the state that already had instanced:
const open = Boolean(menuPosition)
or a i ccould just put in my component argument:
Boolean(menuPosition)
This could help me not declaring more code but this will not be very legible right? Specialy if a needed to use it in more than one place…
thinking about perfomance, memory use and readbilty, what is the best option?
the deravation, creating a new state or using just the Boolean(menuPosition) directly into the component?
2
Answers
The simplest way would be to declare a regular variable in the component’s body. You don’t need
useState
, since it is entirely depending on themenuPosition
.The simplest way:
You can also consider using useMemo to store the value, however, I wouldn’t say that this is necessary since it is just a primitive and isn’t pricey to calculate:
Since open will not trigger any render in your screen, you’ll not need to use a state. Furthermore, as you already have a value for
Boolean
casting and this value is a state, you just need to cast this by adding "!" before the variable, like the following:Another tip: you mustn’t use
Boolean
to type a primitive value in typescript, useboolean
, with lowercase, instead. You can see more about primitive types here Typescript Everyday Types.Since this code is a pretty basic one, I think you are over engineering by thinking so much in performance and memory in this situation.