I cannot figure out what going on with "useSelector" I need little help, please.
ERROR
React Hook "useSelector" is called in function "render_user" which is neither a React function component or a custom React Hook function
class Navigationbar extends Component {
onLogoutClick = e => {
e.preventDefault();
this.props.logoutUser(); //this.props.
};
render() {
const render_user = () => {
const auth = useSelector(state => state.auth); Error Message is here
//More Code Here
);
};
}
Navigationbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ logoutUser }
)(Navigationbar);
The error is due to the fact that you violated the rules of hooks:
- Only Call Hooks at the Top Level
- Only Call Hooks from React Functions
Violations:
useSelector()
is not called in top-level. It is called in render_user()
in render()
(i.e nested function).useSelector()
is part of a class component, Navigationbar
You can extract a component to follow the rules of hooks and make use of useSelector
:
function User() { // Rule 2: call hooks in function component
const auth = useSelector(state => state.auth); // Rule 1: call hooks in top-level
return <>{auth}</>
}
class Navigationbar extends Component {
render_user() {
if (props.authenticated) {
return <User />
}
// not yet authenticated
// do something else
}
render() {
return <>{this.render_user()}</>
}
}
If you are using TypeScript and (obviously) a functional component. Make sure your component name begins with a capital letter and not a lowercase letter.
useSelector is new hook that is added by react-redux after the addition of new Hooks API to react.
These hooks can only be used in function component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With