Socket
Book a DemoInstallSign in
Socket

react-context-mutex

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-context-mutex

Use a mutex lock to prevent callback duplication, now used as a React hook

2.1.1
latest
Source
npmnpm
Version published
Weekly downloads
248
40.11%
Maintainers
1
Weekly downloads
 
Created
Source

react-context-mutex

npm version Build Status codecov

A mutex implementation using React and React context. It will prevent a function from running multiple times, until you allow it to run again. Works in browser and NodeJS.

This was created because I wanted to prevent a fetch from running multiple times after implementing a custom hook in multiple components. The custom hook had a useEffect which ran the fetch function.

Install

$ npm install react-context-mutex

Demo

Edit react-context-mutex

How to use

import { useMutex } from 'react-context-mutex';

const useFetchHook = () => {
    const MutexRunner = useMutex();
    const mutex = new MutexRunner('myUniqueKey1');

    mutex.run(async () => {
        mutex.lock();
        try {
            const response = await fetch('http://myurl');
            const data = await response.json();
            mutex.unlock();
        } catch (e) {
            mutex.unlock();
        }
    });
};

The useFetchHook hook can runs multiple times but the actual fetch is only done once. When the mutex is unlocked again, the fetch can also be executed again.

API

Create a new instance of the mutex runner:

const mutex = new MutexRunner('myUniqueKey1');

Try to run a function. If the mutex is not locked, the resolveCallback will run. If it is locked, the optional rejectCallback will run:

mutex.run(resolveCallback: () => void, rejectCallback?: () => void) => void 
/*
    Usage: mutex.run(() => { yourFunction(); });
    or: 
    mutex.run(
        () => { yourFunction(); }, 
        () => { myMutexIsLocked(); }
    );
    returns void
*/

Lock a mutex:

mutex.lock() // returns void

Unlock a mutex:

mutex.unlock() // returns void

Check if a mutex is locked:

mutex.isLocked() // returns a boolean

Behind the scenes

Behind the scenes there's an array of strings, representing the mutex keys, registered using React context. A new record is added to the array when a process should be locked. Likewise, the record is removed when the process is unlocked.

When using the mutex.run method, there's a check to see if the process is locked or not. If it is, the callback within the mutex.run is abandoned. If the provided key does not reference to a locked process, the callback is executed.

Why React context? Because that way the "mutex store" array will only be initiated once, thus able to use throughout multiple components without causing unwanted collisions.

Keywords

react

FAQs

Package last updated on 23 Oct 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.