Search code examples
reactjsdesign-patterns

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?


Solution

  • Both approaches are valid, but the ternary operator approach can sometimes lead to less readable code, especially if the rendering logic becomes more complex.

    Consistency Consider the coding style and conventions of your team or project. If your team prefers one approach over the other for consistency and readability reasons, it's a good idea to follow that convention.

    However For simple cases like the one you've shown, the ternary operator is concise and clear. However, if the conditional rendering logic becomes more complex, it might be better to use the if statement to keep the code more readable.

    Personal Preference: Ultimately, the choice between the two approaches can also come down to personal preference. Some developers may find the ternary operator more concise and elegant, while others may prefer the explicitness of the if statement.

    In summary, both approaches are valid but it's important to consider the specific context of your project and the preferences of your team when making this decision.