4

I'am working on med sized project and some components in react are created using a class, along with the component level state. For authentication and keeping the token within the local-storage and reloading the user from it, I would use a hook.

I regret this decision now as if you were to refresh on a class component you will lose the user and get kicked back to the login screen.

I know hooks are used for functions but is there a way to use a hook (too keep the user) inside a class?

//The hook I am using

useEffect(()=>{
auth.Context.loadUser();
//eslint-disable-next-line
},[]);
0

1 Answer 1

6

According to React docs you can't use hooks inside a class component:
https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

What you can do is to wrap your class component with a functional component and pass props to it

for example:

class MyClass extends React.Component{
  render(){
    <div>{this.props.user}</div>
  }
}

const funcComp = () => {
  const [user, setUser] = useState();

  useEffect(() => {
    auth.Context.loadUser().then(user => setUser(user))
  }, [setUser]);

  return <MyClass user={user}/>
}


Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.