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

212
Views
How to make a reusable function that calls setUserContext? React Hooks useContext

So I have 4 components that are all doing the same thing inside an onClick handler.

I have to define this code in every single one of them.

The reason I don't know how to make this reusable is that you cannot call setUserContext inside a regular non-react utility function. I tried creating a hook but you cannot use Hooks as callbacks inside onClick.

What are my options here?

  const { userContext, setUserContext } = useContext(UserContext);

  // this goes inside onClick and is defined in like 4 components (too much repetition)
  const favoriteItem = (e) => {
    e.stopPropagation();
    e.preventDefault();
    setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can create a custom hook.

const useCustomHook = () => {


const { userContext, setUserContext } = useContext(UserContext);

  const favoriteItem = (event, game) => {
    e.stopPropagation();
    e.preventDefault();
    setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
  }

return { favoriteItem } 
} 


export default useCustomHook;

Your component can do this.

... 
const { favoriteItem } = useCustomHook() 

return (
<Element onClick={(event) => favoriteItem(event, game)} /> 
) 
... 
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!