Tutorial hero
Lesson icon

Avoid Callback Functions

Originally published June 08, 2023 Time 2 mins

This was a key point from my video on State Adapt, but one I think deserves highlighting on its own. This quote from the creator of State Adapt is worth considering:

When have you ever added an extra line of code to a callback? When you wanted to write imperative code, that’s when. So don’t write callbacks in the first place. The curly braces of functions that don’t return anything are like open arms inviting imperative code.

At first glance, the notion of not using callback functions might seem absurd. But, if we are trying to write declarative code, this is a rule that can serve us well.

Even when trying to write my implementation of Quicklists with State Adapt declaratively, I wrote this callback function for when someone clicks to delete a checklist:

callback function for when someone clicks to delete a checklist

The callback function isn’t such a big deal in itself but, as Mike pointed out, it invites imperative code. I am next-ing a data source here which is fine, but since I am doing this inside of a callback function it was all to easy to add the imperative line of code.

Instead of writing a side effect like this, I could have instead just had my single data source next-ed to indicate the action that just occurred (a particular checklist being deleted).

Then, both of my adapters (the Checklist and ChecklistItems adapters) could have listened for that same event on the data source and both reacted accordingly, rather than requiring the manual imperative step I had initially.

Instead of having the callback function when the delete is triggered, now I can just next the data source and everything reacts appropriately:

next the data source

So, if you want to write more declarative code, try getting rid of as many callback functions as you can.

Learn to build modern Angular apps with my course