Ternary operator inside useState. Is it correct?

Viewed 2943

I am setting a component that receive a specific prop. This prop is the resulting object of a find method on the parent component. The state would be the controller of an input on a form.

When the find method does not find anything, it returns an undefined. I defined my state this way:

const [foo, setFoo] = useState(props.bar? props.bar._id : "");

This works great, but I'm wondering if it's correct to do it like that.

1 Answers

Yes, this is perfectly correct and valid.

I personally, like to create a const initialState to make it a little easier to read.

const Example = (props) => {
  const initialState = props.bar ? props.bar._id : '';
  const [foo, setFoo] = useState(initialState);

  return { foo };
};

As far as accessing _id when bar is undefined. There are a few ways to solve that as well.

One of the new ways to do so is to use the new optional chaining operator ?. and the nullish coalescing operator ?? together.

const initialState = props.bar?._id ?? '';

If you don't have support for those new operators you could also use the || or operator like so.

const initialState = (props.bar || {})._id || '';
Related