mercredi 6 septembre 2023

React: ternary operator or if statement. What is the best approach

Good day. I am sicking wisdom here. I have a tiny example in react code that can be written in two ways:

FetchComponent = ({ url }) => {
  const { loading, data } = useFetch(url);
  if (loading) {
    return <div>Loading...</div>;
  }
  return <div>{JSON.stringify(data)}</div>;
};

or in this way:

const FetchComponent = ({ url }) => {
  const { loading, data } = useFetch(url);
  return (
    <>{loading ? <div>Loading...</div> : <div>{JSON.stringify(data)}</div>}</>
  );
};

As you can see one is using if statement and the other one is using a ternary operator.

So, reaching this point, because we can achieve the same both ways, I wonder what is the better approach, or the react approach or the way of a senior placing the logic in this component example?

Aucun commentaire:

Enregistrer un commentaire