Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
how to make a custom hook being executed once globally

I have a hook that adds a header tag in order to load a script, but in case two components are using it, the hook could fall into the case that the header is added twice.

There are several ways to avoid this. Two of them could be:

  1. Use a provider, not a hook that several components could call. Actually I don't want this, I want a hook because at most two components will use it, and in some cases I don't even need it;
  2. The hook calls a function called const addHeaderTag = () => {...}. I could add a property to it and check if the function is called just once, otherwise return silently. It could be safe because the function is defined by me and I control the function object, plus javascript is monothread and concurrency is out of scope;
  3. I could add an id to the header so as to check if it's on the DOM already. I'd avoid it in order to not access the DOM too much

Do you see other better ways? Do you see any problem to the solutions I had in mind?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

A solution for this would be using a variable outside of your custom hook to check whether or not your hook is already called

import { useEffect } from "react";

let isCalled = false;

export const useOnce = () => {
  useEffect(() => {
    if (!isCalled) {
      // do this only once, call your function here
      console.log("hey there");
      isCalled = true;
    }
  }, []);

  return isCalled;
};

The reason this works is because when you import the same module multiple times, the code in that module is still only evaluated once. That means isCalled in this case is only initialized once, so we can depend on it to check/set the value accordingly for the entire app.

Live example

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!