Immediately Invoked Function Expressions for Conditional Rendering in React

Henry Rossiter
2 min readSep 4, 2020

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

How to use an IIFE

IIFEs can be used to conditionally assign values to immutable variables. This is achieved using an unnamed function that is evaluated exactly once when the variable is declared. Here’s an example of an IIFE:

const dayOfWeek = 'wednesday';const isTodayWednesday = (() => {
if (dayOfWeek === 'wednesday')
return true;
return false;
})();

Of course, we could always create the function as a separate variable. The code below achieves the same effect as the IIFE above:

const dayOfWeek = 'wednesday';const myFunction = () => {
if (dayOfWeek === 'wednesday')
return true;
return false;
}
const isTodayWednesday = myFunction();

In this case, however, we’ve added an additional variable, myFunction to our namespace.

We could also use a ternary operator to achieve the same effect:

const dayOfWeek = 'wednesday';// Assignment with ternary operator
const isTodayWednesday = dayOfWeek === 'wednesday' ? true : false

When the assignment logic is more complicated, however, it may not be possible to use the ternary operator.

IIFEs for Conditional Rendering

It is possible to use IIFEs to achieve clean, deterministic rendering in React and React Native. In the example below, I create a Component that renders text conditionally based on the status prop:

const MyComponent = (props) => {
const textStyle = (() => {
if (props.status === 0){
return { color:
'#ff0000' };
}
else if (props.status === 1) {
return { color:
'#00ff00' };
}
return { color:
'#ff0000' };
})();
const textContent = (() => {
if (props.status === 0 || props.status === 1){
return 'status is 0 or 1';
}
return 'error, status was not 0 or 1';
})();
return (
<
Text style={textStyle}>
{textContent}
</
Text>
);
};

In the example above, the variables textStyle and textContent are assigned exactly once each time MyComponent is rendered.

--

--