So I have a custom hook, which I want to use at multiple places in another components like a function, which takes in parameter (E.i For useNavigate() from react-router-dom-v6, we use it as const navigate = useNavigate() then navigate('./url/to/navigate') can be used at multiple places).
But in the custom hook, I want to process that parameters value through another custom hook. This is what I tried but React does not allow me to have hooks inside function like so:
//useCustomHook.js
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
...
export default function useCustomHook() {
function processingData(currentState){
const previousState = usePrevious(currentState); //React does not allow to have hook here
return process(currentState, previousState);
}
return processingData;
}
//Component.js
...
const cusHook = useCustomHook();
...
useEffect(()=>{
cusHook(state1)
},[])
useEffect(()=>{
cusHook(state2)
},[temp])
Is there a way I can achieve this?
No, there is no way you can use hook inside pure javascript function. Why not doing something like this:
export default function useCustomHook(currentState) {
const previousState = usePrevious(currentState);
const processingData = () => {
return process(currentState, previousState);
}
return processingData;
}