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

99
Views
Is there a way to put react hooks in a function that's not function component?

I'm trying to create a function that is not a component nor hooks that's callable on speficic event. Let's say i have a simple function that post a data using axios and i want to use navigate after the post is successfull. Here's the example

export const authLogin = (email, password) => {
    const config = {
        withCredentials: true,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRFToken': Cookies.get('csrftoken')
        }
    }

    let navigate = useNavigate();

    return dispatch => {
        console.log('Masuk ke dalam auth file');
        dispatch(authStart());
        axios.post('/log_in/', {
            email: email,
            password: password
        }, config)
            .then(res => {
                if (res.data.error) {
                    alert(res.data.error)
                    dispatch(authFail(res.data.error))
                }
                else {
                    const token = res.data.key;
                    const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
                    localStorage.setItem('token', token);
                    localStorage.setItem('expirationDate', expirationDate);
                    dispatch(authSuccess(token));
                    dispatch(checkAuthTimeout(3600));
                    alert('login berhasil')
                    navigate("/", { replace: true });
                }

            })
            .catch(err => {
                alert(err);
                dispatch(authFail(err))
            })
    }
}

I have an error that says enter image description here

but when i try to change the function name with an uppercase letter, another problem occured, how do i resolve this problem?enter image description here

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A hook must be attached to a fiber which is directly attached to the React component tree. You CANNOT use hooks outside the component tree because React can't keep track of them (this is why hooks must always be run in the same order, and can't be conditional, because React keeps track of their state internally).

The only time you can use a hook outside of a component, is from another hook.

In short, you must be able to draw a straight line back from the hook call to React rendering the component tree. If you cannot, then it's an invalid hook call.

THE SOLUTION

...in your case - is to simply pass in the navigate function to your action as a parameter:

const MyComponent = () => {
 
   const navigate = useNavigate();

   const doSomethingHandler = () => {
      dispatch(authLogin(email,password,navigate))
   }

}


const authLogin = (email,password,navigate) => {

    // ...do your action and call the `navigate` parameter
    // when you need to
}

about 4 years ago · Santiago Trujillo 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!