6 min read
Managing UI decision complexity - from boolean soup to business rules
Conditions inline in JSX get hard to follow. A small, type-checked rules object turns them into named flags you can test.
In software development, we often need to check multiple conditions in one step, be it a frontend component or a backend function. In frontend development it will mostly decide about UI state. Let's say there are multiple conditions incoming from different parts of the system: user permission levels, user subscription plan, entity state, etc.
Usually frontend code grows with the complexity of product's business logic. This often starts as a simple conditional statements like so:
import React from 'react'
export const App = () => {
// authentication logic here
const authenticated = useIsAuth()
// decide which view to show
return authenticated ? <PrivateRoutes /> : <PublicRoutes />
}
That is very basic conditional logic for displaying private routes only to authenticated (logged in) users.
When things get complicated
Previous example was very rudimentary. Complexity can grow very quickly as business requirements grow and evolve in Scrum environment. It’s highly likely more conditions will be added to app’s business logic and be required to check for proper UI display. For this let’s use example of Meta’s Messenger app and the single message entity.
First, we define a simple Message entity with all its relevant properties and context:
type Message = {
id: string
senderId: string
recipientId: string
sentAt: Date
deliveredAt?: Date
seenAt?: Date
deleted: boolean
failed: boolean
attachmentsCount: number
isPinned: boolean
isEdited: boolean
isReply: boolean
isGroupMessage: boolean
currentUserId: string
}
Below is a table of conditions that control how the UI behaves for each message:
| Condition name | Description | Example Logic |
|---|---|---|
isSent | Has the message been sent successfully? | !!message.sentAt && !message.failed |
isDelivered | Was the message delivered (but maybe not seen)? | !!message.deliveredAt && !message.seenAt |
isSeen | Has the message been seen by the recipient? | !!message.seenAt |
canEdit | The sender is current user and message is not deleted or failed. |
|
showPinnedIcon | Message is pinned in chat. | message.isPinned |
showEditedIndicator | The message was edited. | message.isEdited |
showReplyPreview | The message is a reply to another message. | message.isReply |
showAttachmentIcon | The message has attachments. | message.attachmentsCount > 0 |
showDeleteButton | Current user is sender or group admin, and message is not deleted. |
|
showFailedIcon | Show error indicator if failed to send. | message.failed |
Visual mapping
- If
showFailedIcon→ show red error icon and retry option. - If
isDeliveredbut notisSeen→ show double-check icon in gray. - If
isSeen→ show double-check icon in blue. - If
canEdit→ show edit button. - If
showPinnedIcon→ display pin in corner. - If
showReplyPreview→ show small reply preview UI.
Now let’s see how this could be implemented without any clever refactors - just growing codebase overtime.
import {
Attachment,
Check,
DoubleCheck,
EditPencil,
Pin,
Reply,
WarningTriangle,
} from 'iconoir-react'
import type React from 'react'
import type { Message } from './types'
type MessageProps = {
message: Message
userIsGroupAdmin: boolean
}
export const OldFlagsMessage: React.FC<MessageProps> = ({
message,
userIsGroupAdmin,
}) => {
const isSent = !!message.sentAt && !message.failed
const isDelivered = !!message.deliveredAt && !message.seenAt
const isSeen = !!message.seenAt
const isFailedToSend = message.failed
const canEdit =
message.senderId === message.currentUserId &&
!message.deleted &&
!message.failed
return (
<div>
<p>Message ID: {message.id}</p>
{message.isReply && (
<div>
<Reply /> Replying to a message
</div>
)}
{message.attachmentsCount > 0 && (
<div>
<Attachment /> {message.attachmentsCount} Attachment(s)
</div>
)}
{message.isEdited && (
<span>
<EditPencil /> Edited
</span>
)}
{message.isPinned && <Pin />}
{isFailedToSend && <WarningTriangle />}
{isSeen ? (
<DoubleCheck className='text-primary-text' />
) : isDelivered ? (
<DoubleCheck className='text-muted-foreground' />
) : isSent ? (
<Check className='text-muted-foreground' />
) : null}
{canEdit && <button type='button'>Edit</button>}
{(message.senderId === message.currentUserId || userIsGroupAdmin) &&
!message.deleted && <button type='button'>Delete</button>}
{isFailedToSend && <button type='button'>Retry</button>}
</div>
)
}
Five named flags, and then half of the conditions live inline in the JSX anyway: message.attachmentsCount > 0, the sender check in the delete button, the nested ternary for the ticks. Nothing tells you that the delete button and canEdit share a rule. Nothing stops the next person from writing a third copy of the same condition, worded slightly differently.
From terrible mess to terribly clever
The code above is less than ideal especially around readability: some conditions have names, some do not, and the JSX is where they all meet. As a first step one could certainly refactor all those checks into hooks. But let’s go deeper into this refactor as business requirements will certainly grow as the only constant in life (and especially in software development) is change. The death and taxes are just a derivative of that.
So we want a refactor that holds up as requirements grow and that can be used in other places of the system if necessary. The latter is especially good requirement because making this a bit more top level and detached from the very business logic allows to sharing responsibility for this code among many team members. Easing code maintenance and benefiting from sharing idea around this solution.
There are few things those conditions have in common:
- result is boolean flag
- each depends only on the payload, never on the result of another flag
- they depend on limited source of truth - deciding data passed to the component is a limited set
All this tells us there is solution to this problem that could be expressed as
type Rule<Payload> = (payload: Payload) => boolean
If we could define all boolean flags as such functions, we could include them in a data set, run each function with the same payload and collect the result for each flag. If this is not clever then I hate React.
So, inspired by eslint rules and cva props evaluation, I created a simple engine that takes an object of rules (not nested) and runs each function with provided props. Each Rule is represented with its name, and the function that returns boolean. The function evaluates the incoming props and returns a boolean value: a Flag.
export type Rules<A, K extends string = string> = Record<
K,
(args: A) => boolean
>
export type Flags<K extends string = string> = Record<K, boolean>
A is the payload every rule receives. K is the set of flag names.
Modeling these conditions as a rules object
With the above pattern we can create a set of functions - in this case in an object:
//basically component props in our case
export type MessageRulesArgs = {
message: Message
userIsGroupAdmin: boolean
}
import type { MessageRulesArgs, Rules } from '../types'
export const messageRules = {
isSent: ({ message: m }) => !!m.sentAt && !m.failed,
isDelivered: ({ message: m }) => !!m.deliveredAt && !m.seenAt,
isSeen: ({ message: m }) => !!m.seenAt,
canEdit: ({ message: m }) =>
m.senderId === m.currentUserId && !m.deleted && !m.failed,
showPinnedIcon: ({ message: m }) => m.isPinned,
showEditedIndicator: ({ message: m }) => m.isEdited,
showReplyPreview: ({ message: m }) => m.isReply,
showAttachmentIcon: ({ message: m }) => m.attachmentsCount > 0,
showFailedIcon: ({ message: m }) => m.failed,
showDeleteButton: ({ message: m, userIsGroupAdmin }) =>
(m.senderId === m.currentUserId || userIsGroupAdmin) && !m.deleted,
} satisfies Rules<MessageRulesArgs>
satisfies checks every rule against Rules<MessageRulesArgs> and gives the parameters their types, but keeps the object's own literal keys. There is no second list of flag names to keep in sync.
With rules defined the remaining thing to do is evaluate the result with our data. For this I came up with this little helper:
import type { Flags, Rules } from '../types'
export const applyRules = <A, K extends string>(
rules: Rules<A, K>,
args: A,
): Flags<K> =>
Object.fromEntries(
Object.entries<(args: A) => boolean>(rules).map(([name, rule]) => [
name,
rule(args),
]),
) as Flags<K>
The single as is there because Object.fromEntries loses the key names. It returns { [k: string]: boolean }, so we put them back.
Both A and K are inferred from the call. A misspelled flag or a wrong payload is a compile error:
// error: Property 'isSnet' does not exist
const { isSnet } = applyRules(messageRules, { message, userIsGroupAdmin })
// error: 'nonsense' does not exist in type 'MessageRulesArgs'
applyRules(messageRules, { nonsense: 1 })
Every flag is typed as boolean.
Final usage in React component. There is no hook and no useMemo. Ten cheap boolean checks run on each render, and the results are destructured into primitives at once, so there is no object identity worth keeping. Reach for useMemo when a single rule gets expensive.
import {
Attachment,
Check,
DoubleCheck,
EditPencil,
Pin,
Reply,
WarningTriangle,
} from 'iconoir-react'
import type React from 'react'
import { applyRules } from './rules/apply-rules'
import { messageRules } from './rules/rules'
import type { Message } from './types'
type MessageProps = {
message: Message
userIsGroupAdmin: boolean
}
export const WithRulesMessage: React.FC<MessageProps> = ({
message,
userIsGroupAdmin,
}) => {
const {
isSent,
isDelivered,
isSeen,
canEdit,
showPinnedIcon,
showEditedIndicator,
showReplyPreview,
showAttachmentIcon,
showFailedIcon,
showDeleteButton,
} = applyRules(messageRules, { message, userIsGroupAdmin })
return (
<div>
<p>Message ID: {message.id}</p>
{showReplyPreview && (
<div>
<Reply /> Replying to a message
</div>
)}
{showAttachmentIcon && (
<div>
<Attachment /> {message.attachmentsCount} Attachment(s)
</div>
)}
{showEditedIndicator && (
<span>
<EditPencil /> Edited
</span>
)}
{showPinnedIcon && <Pin />}
{showFailedIcon && <WarningTriangle />}
{isSeen ? (
<DoubleCheck className='text-primary-text' />
) : isDelivered ? (
<DoubleCheck className='text-muted-foreground' />
) : isSent ? (
<Check className='text-muted-foreground' />
) : null}
{canEdit && <button type='button'>Edit</button>}
{showDeleteButton && <button type='button'>Delete</button>}
{showFailedIcon && <button type='button'>Retry</button>}
</div>
)
}
Same JSX, same layout. The only difference is that every && now reads a name.
When a plain function is enough
For one component, you do not need the rules map. A function that returns an object literal gives the same named, testable flags with less machinery, and TypeScript infers every key:
import type { MessageRulesArgs } from './types'
export const getMessageFlags = ({
message: m,
userIsGroupAdmin,
}: MessageRulesArgs) => ({
isSeen: !!m.seenAt,
canEdit: m.senderId === m.currentUserId && !m.deleted && !m.failed,
showDeleteButton:
(m.senderId === m.currentUserId || userIsGroupAdmin) && !m.deleted,
// ...and the rest of the flags
})
The rules map earns its place when the rule set is data. It is shared between components, overridden per context by spreading ({ ...messageRules, canEdit: … }), or iterated, for example by one table-driven test over Object.entries(messageRules). If you do none of that, use the function.
Benefits of this approach
- Clarity: Each condition is named and easy to understand.
- Reusability: Components that need the same rules can import the object instead of copying conditions. Overriding one rule is a spread.
- Testability: Each rule is a pure function of the payload, so it can be tested alone. One table-driven test can cover the whole set.
- Extensibility: Adding a rule is one entry in the object. The new flag shows up in the types without any other change.
Conclusion
If you find yourself with growing UI complexity and a web of conditions, consider abstracting those checks into a rules object or lightweight engine. It brings structure, clarity, and scalability to what would otherwise become a nightmare of conditionals and a spaghetti code.