0

In my component I use a function which I want to extract, it uses some hooks for setting url params. I created a custom hook.

function useMyCustomHook() {
    const history = useHistory();
    const location = useLocation();
    const locationParams = new URLSearchParams(location.search);

    function myCustomHook(id: string ) {
        does something
    }

    return myCustomHook;
}

So I extracted it like shown above and now I want to use it in my other component and inside a useEffect hook.

const { myCustomHook } = useMyCustomHook(); // It asks me to add parameters, 
    but I want to pass it inside useEffect
        
            useEffect(() => {
                if (something) myCustomHook(myParam);
                
            }, [foo]);

Is this a possible approach? Or is there a better solution where I can extract something with hooks and then reuse it in useEffect with parameters? Thank you!

1 Answers1

0

First you need export your custom Hook, I think if you need return a function with id, that function need be executed each id change.

custom hook

import { useCallback} from "react"
import {useNavigate, useLocation} from "react-router-dom"

export const useMyCustomHook = (id) => {
  const navigate = useNavigate() // React-router v6
  const location = useLocation()
  const locationParams = new URLSearchParams(location.search)

  const anyFunction = useCallback(() => {
    // does something
  }, [id]) // the function execute if "id" change

  return anyFunction
}

where you wanna use your custom hook

import {useMyCustomHook} from "your router"
    
const {anyFunction} = useMyCustomHook(id) // your pass the id

useEffect(() => {
  if  (something) anyFunction()
}, [foo])

I think this is the better way. useCallback only render the function of the params change.