Front End Race Conditions

Front End Race Conditions

Race conditions are the bogeyman of concurrent programming. When they happen, they are hard to spot and even harder to reproduce.

Races can happen any time you have concurrent processes operating on the same data – especially without going through an explicit synchronization mechanism.

Having worked with threads, coroutines, semaphores, mutexes, locks and other abstractions across a handful of different programming languages, I’ve caused my fair share of race conditions. So typically, I’m extra vigilant when working with concurrent code.

As a result, a recent situation caught me by surprise when working in React. I don’t always think explicitly about concurrency in Javascript, but as soon as you introduce a callback or an event, there it is.

In this particular case I was building a cancellable delete animation.

To cause the race you have to start deleting a second element before the first has completed. This could be very easily overlooked and it is easier to spot if we slow the animation down.

The array index of the element you intended to remove will change any time an item before it is removed. If the index changes during the animation the wrong element is removed.

The solution in this case was to add a unique identifier rather than an index to control the removal of elements.

Front end code is asynchronous due to callbacks and events. Front end component state is shared memory. These two features together are a recipe for race conditions, so keep an eye out, and be careful out there.

If you’d like to see a live example of this code, you can find it here:
https://codepen.io/simplethread-sam/pen/mdrVgWo

Loved the article? Hated it? Didn’t even read it?

We’d love to hear from you.

Reach Out

Comments (1)

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More Insights

View All