Home > Enterprise >  How to make a reusable function that calls setUserContext? React Hooks useContext
How to make a reusable function that calls setUserContext? React Hooks useContext

Time:09-26

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")) });
  }

CodePudding user response:

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)} /> 
) 
... 
  • Related