Avoiding state update on unmounted React component within useEffect hook

The hooks introduced with React 16.8 are a nice way to control state and other features on functional React components. They discard the necessity of third-party libraries such as Recompose – which is the inspiration for React hooks, by the way.

One way one can apply the useEffect hook, for example, is to mimic the behavior of componentDidMount event to bind a value returned by an asynchronous function to a given state. Like:

const React, { useEffect, useState } from 'react';

export default Component = () => {
    const [ data, setData ] = useState(null);
    useEffect(() => {
        (async () {
            setData(await someAsyncApiCall());
    }, []);
    return (<span>{ data }</span>);

Calling the useEffect hook with an empty array will make it be called only when the component was mounted, i.e. is the same as componentDidMount event.

However, if the component has unmounted some point before the async call finishes, it’s likely to get the following error in the console:

Can’t perform a React state update on an unmounted component

That happens because the async function called setData, which is the state setter, after the component has unmounted. To fix that error, it’s required to cancel the async function before changing the state in case the component did unmount.

In a “regular” React component, there is the componentWillUnmount event. One could set a flag to indicate the component is not mounted anymore to avoid setting the state late. Simulating this same approach with hooks is not hard. A function returned by a useEffect hook with an empty array in the second argument (the case above) run when the component will unmount. So, one could have the following:


export default Component = () => {
    const [ data, setData ] = useState(null);
    useEffect(() => {
        let mounted = true; // Indicate the mount state
        (async () {
            const data = await someAsyncApiCall();
            if (!mounted) return; // Exits if comp. is not mounted
        return () => { // Runs when component will unmount
            mounted = false;
    }, []);

Now the error is gone since the state is not updated if the component is not mounted anymore.

I particularly am fond of hooks. I used to add Recompose to projects in the past and like the way the code looks with functional components. There is also, the performance benefits.

If you have questions or suggestions, feel free to express yourself in the comments below.

Custom setters with React useState hook

One of the recent additions to React was its hooks. With that, developers don’t need to rely on libraries such as Recompose to add state (and other features) to functional components.

If you’re one of those devs and were used to create custom setters for states, it’s possible you find the new useState hook somewhat limited. But you still can write your own setters, wrapping the setter returned by useState into another function.

Consider the following Recompose code:

    counter: 0,
}, {
    increment: ({ counter }) => {
        return () => ({
            counter: counter + 1,
    decrement: ({ counter }) => {
        return () => ({
            counter: counter - 1,

You may write the same logic with React hooks this way:

const [ counter, setCounter ] = useState(0);
const increment = () => {
    setCounter(counter + 1);
const decrement = () => {
    setCounter(counter - 1);

This probably seems pretty obvious but there are some cases where you may need to apply some side-effect to your setter and this approach would be useful. Here it goes an example, given the same state above:

const [ counter, _setCounter ] = useState(0);
const setCounter = (counter) => {
    // Some side-effect here ...
    // ... or there

For questions and suggestions, please leave a comment below.

Checking DNS records of a specific nameserver

I’m migrating a site from GoDaddy to HostGator (I personally would prefer to move over AWS but that’s the client’s choice in this specific case) and I wanted to get the IP of the new server on HostGator. I couldn’t find the IP anywhere on their control panel. Pinging the temporary URL they provide for testing was returning a different address — I suspect they have some kind of proxy in place for this temp URLs.

I know the host command could give me the DNS settings, which would include the A record with the IP address. However, the domain was still set to use GoDaddy’s nameservers (NS). Running host "name.tld" would give me the DNS records from GoDaddy. However, I was wondering if I could run the command against a specific nameserver. It makes sense having a way to look for records that way, right?

Looking at the man page for host command, there is a server argument. The signature looks like host [options] host [server]. So, I ended up running:

host -a "name.tld" "new.nameserver.tld"

And, voilà! I got the IP address for the new web server.

Got questions? Feel free to comment below.

Laravel and NodeJS messaging using Redis Pub/Sub





Subscribing to a channel


    /* Do whatever you need with the message */


class Subscriber extends Command
    protected $signature = 'redis:subscriber';

    protected $description = '...';

    public function handle()

    public function processMessage(string $message)
        /* Handles the received message */



'read_write_timeout' => 0,
'persistent' => 1,

Publishing to the channel


$ npm install redis


const redis = require('redis');
const client = redis.createClient();

const handler = (event, context) => {
    const message = processEvent(event);
    client.publish('channel_name', message);
    return context.done(null, {

const processEvent = (event) => {
    return event.message;

exports.handler = handler;


Testing all together


$ php artisan redis:subscriber


const http = require('http');

// This is where the Lambda function is
const lambda = require('./lambda');

const context = {
    done: (error, success) => {
        if (error) {
            console.error('FAIL:', error);
        console.log('OK:', success);

    let data = '';
    request.on('data', (chunk) => {
        data += chunk;
    request.on('end', () => {
        if (data) {
            const event = JSON.parse(data);
            lambda.handler(event, context);





$ node web.js

And then invoke the function with cURL:




OK: { message: 'Hello world!' }

And another from the Artisan command:

Message received: Hello world!





Got comments or questions? Feel free to share them below.

Using MutationObserver API and undo.js to track DOM changes

I was recently working on this project that had a kind of drag and drop builder. Users should be able to drag items into a specific building area to assembly stuff — I’m sorry for not giving more details, by the time I’m writing this the product is not yet released. One of the features I had to implement was a pair of buttons to undo and redo actions.

Every time an item is added to the builder, a DOM change happens. So, I started to look for ways to track changes in the DOM. That’s when I found about MutationObserver API. That web API is implemented by most of the modern browsers, Internet Explorer 11+ included, and allows you to observe DOM changes using a simple approach. The second tool that helped me build this was undo.js. It’s a simple Javascript class that allows developers to implement actions tracking in an exceptionally easy way.

After coding this feature, it seemed to me that combination of tools might be useful for a lot of other use cases. So I wrote this fiddle to demonstrate how they can be used together:


If you have any question, the comments area below is all yours.

Testing Stripe webhooks when using Laravel Cashier

I’m not sure why this is not in the docs, but if you’re using Laravel Cashier and want to test Stripe webhooks – in test, not live, mode – you have to set the following env var:


I’ve spent some time checking around my code until I found that.

Using make to build a NodeJS app

Do you know you can use the good ol’ make to build your NodeJS app? I wrote a little about it in my latest post on Kettle’s Blog:


Injecting controller actions in Laravel views

Disclaimer: Depending on the kind of logic you need, it’s also possible to use View Composers to achieve a similar result.

I’m using Laravel in this new project I’m working on. Some other PHP frameworks have a feature to use controllers as services. Symfony, for instance, has something like that. The project team thought Laravel, as Symfony-based, would have something like that. Well, if it has, it’s not clear in the docs.

Another team member ended up with a solution I never thought before:

 @inject('someController', 'App\Http\Controllers\SomeController')
 {!! $someController->index() !!}

Now, we’re using Blade’s @inject directive to call controller actions from inside views. That’s useful for reusing actions as widgets, for example.

If you find that interesting and want to use in your application, remember two things:

  1. Since you’re calling the action method directly, you have to pass all the required params. If it expects a request instance, you can do this: $someController->index(request()).
  2. Probably the method returns a view that contains HTML code. So wrap the call within {!! and !!}. Using the {{ }} regular tag will cause the code to be escaped.

Implementing an SDK compatible with Laravel Container Service

When developing an SDK — and by SDK I mean an API implementation — you can leave for your users the task of integrating it with their apps. However, it’s a good idea to make it compatible with trendy frameworks out of the box.

In the PHP world, Laravel is becoming a very popular choice of framework. I want to share how you can make your SDK compatible with its Service Container.

The API client

For the sake of example, let’s imagine your API client class looks like this:

class Client
    public function __construct($username, $password)
        // Set up client.

Maybe you have a different way to set up API configuration. Anyway, it’s a good idea to have them set through a method, and not directly via a config file or other env-depending method. Using a method will make it easy to pass the settings from user’s app to the SDK. Also, it makes the configuration process more abstract and easier to plug-in.

The config file

In the sample client above, we have to pass a username and password to create a new instance. It’s clear we need to get that from somewhere. When using the SDK directly, you may do the following:

 define('API_USER', 'username');
 define('API_PASSWORD', '***');
 $client = new Client(API_USER, API_PASSWORD);

Since our goal is to inject the API implementation into the app, it’s better to config that using the framework way. Laravel stores application settings in different files inside a config dir. We can create a file like those to store the API settings:


return [

    // The API user.
    'username' => 'username',

    // The API password.
    'password' => '***',


Even better than set plain values to that config array, it’s using env vars. Laravel is shipped with PHP dotenv. It allows each environment to have its own settings without any change in the application code. So, let’s change our config file a little bit:


return [

    // The API user.
    'username' => env('API_USER'),

    // The API password.
    'password' => env('API_PASSWORD'),


The vars we’re using here have a very generic name. You should use a more specific name to avoid conflicts with other services. Something like DUMMY_API_USER, for an API called Dummy, for example.

The Service Provider

According to Laravel docs:



We have to create a service provider to tell Laravel that our API client can be injected as a dependency into application classes and methods. Also, the service provider will be in charge to merge the API configuration into the application configs.

It will look like this:

use Illuminate\Support\ServiceProvider;

class ApiServiceProvider extends ServiceProvider

    public function boot()
            __DIR__ . '/config.php' => config_path('api.php'),

    public function register()
        $this->mergeConfigFrom(__DIR__ . '/config.php', 'api');

        $this->app->singleton('api.config', function ($app) {
            return $this->app['config']['api'];

        $this->app->singleton(Client::class, function ($app) {
            $config = $app['api.config'];
            return new Client($config['username'], $config['password']);

    public function provides()
        return [

In the boot method, we tell to Laravel which config files can be published to application’s config dir. So users of our API can overwrite those settings.

Within the register method, the service provider binds the config and the API client instance into the service container.

To improve performance, we use the provides method to let the framework know what are the binds this service provider offers. This way, it will only try to resolve the bind when it’s actually needed.

Using the service provider

After you added the SDK to the application, probably using Composer, you have to register its service provider. Open the config/app.php file of the app and add the service provider to the providers array:

$providers = [
    // ...


Now you can inject the API client into the app classes, like controllers:

class UserController extends Controller
    public function show(Client $client)
        $user = $client->getUser();
        return view('user.show', [ 'user' => $user ]);

To set the API username and password, you have to publish the config file:

$ php artisan vendor:publish --provider="ApiServiceProvider"

Then edit the config/api.php file if needed. This file may have another name if you changed its name in the service provider, which you should do.

You also may want to create the env vars inside the application’s .env.example and .env files.


Making your API SDK compatible with Laravel is very simple and requires only one extra class. It worth adding that to reach more users and make their work easier.

P.S.: I’ve omitted some implementation details and stuff like namespaces in the samples above. You can find a complete functioning example in Github: https://github.com/straube/dummy-sdk.

Documenting or not

There are lots of people talking about the importance of writing code documentation. Some, otherwise, advocate in favor of not documenting at all. These usually say your code must tell the history by itself. I’d like to make my own statement in this matter: I agree with both sides in this discussion.

I love to write code documentation. And sometimes, no matter how much I try to make my code be expressive, I need the support from something more textual. I guess that’s due to my code-writing style. I prefer to use a concise naming to my symbols. Instead of `getAllOrdersFromUser(user)`, I’d rather to use `getOrders(user)`. Unless the context requires a meaningful name, the latter is enough expressive. It says what the function does — gets orders — and based on what — a user. For this example, writing what the function actually does is not so important. I can then omit the doc block. In other cases, though, there are some logic details that can be hidden behind a weak name. For those, a statement on what that piece of code does may be essential for understanding.

Yet, for some projects, I struggle keeping docs up-to-date. This happens especially when I’m writing something that must be deployed ASAP. Or when working with pairs that don’t care about documenting. You should know, real life not always allows you to do everything in the way you want to. If I don’t plan to keep my code and documentation in sync, I do not write a comment that won’t say a thing about the code next to it. It’s preferable having no doc than something that will confuse other dev or even myself.

There is a place in the middle of these two points of view where the day-by-day programming resides. Writing expressively is the better way to coding. But, if you’re adding documentation keep in my mind you must update it constantly as your logic changes.