Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React : is it bad to use a hook in a normal function?

So i have this react functional component :

import { createContext, useContext, useState } from 'react';
const GeneralContext = createContext();
export function GeneralContextWrapper({ children }) {
  const [userSessionExpired, setUserSessionExpired] = useState(false);
  return (
    <GeneralContext.Provider
      value={{
        userSessionExpired,
        setUserSessionExpired,
      }}
    >
      {children}
    </GeneralContext.Provider>
  );
}

export function useGeneralContext() {
  return useContext(GeneralContext);
}

I have to change the state of userSessionExpired in a normal function so i do :

const checkToken = (data) => {
  const { userSessionExpired, setUserSessionExpired } = useGeneralContext();
  if (data.status === 'fail' && data.message === 'Sessione scaduta') {
    window.location.href = '/auth/login?session=expired';
    localStorage.removeItem('jwt');
  }
  return data;
};

And i got eslint warning :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

React Hook "useGeneralContext" is called in function "checkToken" that
is neither a React function component nor a custom React Hook
function. React component names must start with an uppercase letter.

where i call the checktoken function example in a fetch call :

export const call = async (url, token, data) => {
  const dataReturned = await fetch(url, {
    method: 'PUT',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      return { status: 'fail', message: 'API CALL ERROR', error: err.message };
    });
  return checkToken(dataReturned);
};

I would like to know if i can ignore the warning or not?

>Solution :

It’s unclear how your checkToken is ever called, but you surely shouldn’t be using any hooks from within an async function. In order for hooks to work properly, they have to be called in the same order every time the component renders, and if a call is originating from within an async function, it’s almost guaranteed that’s not going to happen.

The warning you’re seeing is good advice, and you should heed it. Call your hooks within your component (or within other hooks that you create), and then if you have a function that needs the result of those hooks (in your case, a context), then pass that into the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading