In my react js application i have 2 components, in one component i have a button and in second i want to get the moment when user clicks the button. For this i created a context where i have 2 functions, one allow user using it with the button, and second one is used in another component.
Context
import React, { createContext, useContext, useRef, useMemo } from "react";
// Define context properties
const ActionsContext = createContext();
export const ActionsProvider = ({ children }) => {
const triggerCallbackRef = useRef(null);
// Function to register the callback
const registerCallback = (callback) => {
triggerCallbackRef.current = callback; // Store the callback
};
const value = useMemo(
() => ({
onGetAction: () => triggerCallbackRef.current,
onTrigerAction: registerCallback,
}),
[]
);
return (
<ActionsContext.Provider value={value}>{children}</ActionsContext.Provider>
);
};
// Custom hook to use the PageActions context
export const useActions = () => {
const context = useContext(ActionsContext);
if (!context) {
throw new Error(" must be used within a Provider");
}
return context;
};
import React, { useEffect } from "react";
import { useActions } from "./context";
const MyComponent = () => {
const { onTrigerAction } = useActions(); // Get the register function
return <button onClick={onTrigerAction}>click</button>;
};
export default MyComponent;
import React, { useEffect } from "react";
import { useActions } from "./context";
const MyOtherComponent = () => {
const { onGetAction } = useActions();
onGetAction(() => {
console.log("button is cliked");
});
return "Hello";
};
export default MyOtherComponent;
<ActionsProvider>
<MyComponent />
<MyOtherComponent />
</ActionsProvider>
I expect to trigger the console log here
onGetAction(() => {
console.log("button is cliked");
});
but nothing happens when i click.
How to fix?
2
Answers
You seem to have your object properties mixed up, your
onGetAction
should register your callback, and thenonTrigerAction
should trigger the callback stored in your ref (if it’s set). You currently have it the wrong way around and also need to change it so you’re invoking the callback stored incurrent
with()
:you have to do something like that
in this part you creating state using context hook.
here you are calling the context api.
and update the state this will trigger your callback automatically.