In React, hooks like useState cannot be called outside of a functional component or another hook. The useState calls you have at the top level of your code are invalid. These calls need to be inside a component or a custom hook.
To fix this, you can either move the state into the App component or create a custom hook that manages the state and provides a way to show the snackbar.
Here’s how you can refactor your code to keep the functionality while resolving the invalid hook call issue:
- Move the state into the
App component.
- Update your
message function so it can work within the component.
Here’s the refactored code:
import React, { useState } from "react";
import { Appearance, StyleSheet } from 'react-native';
import { Snackbar, MD3LightTheme as DefaultLight, MD3DarkTheme as DefaultDark, PaperProvider } from 'react-native-paper';
import Navigation from './StackNavigator';
import * as Theme from './themes';
let showMessage; // This will hold our message function
export default function App() {
const [snackbarVisible, setVisible] = useState(false);
const [snackbarText, setText] = useState('');
// Define the message function inside the component
showMessage = (message) => {
setVisible(true);
setText(message);
};
return (
<PaperProvider theme={Appearance.getColorScheme() === 'light' ? Theme.lightTheme : Theme.darkTheme}>
<Navigation />
<Snackbar
visible={snackbarVisible}
onDismiss={() => setVisible(false)}
action={{
label: 'Undo',
onPress: () => {
// Do something
},
}}
>
{snackbarText}
</Snackbar>
</PaperProvider>
);
}
// Export the showMessage function so it can be used elsewhere in your app
export function message(message) {
if (showMessage) {
showMessage(message);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Explanation:
-
State Management: By moving const [snackbarVisible, setVisible] = useState(false); and const [snackbarText, setText] = useState(''); inside the App component, the state is now managed within a component.
-
message Function: The message function is refactored to be defined inside the App component and assigned to a variable (showMessage), which is then exported so it can be used elsewhere in your app.
-
Snackbar Update: The Snackbar's onDismiss method is updated to hide the snackbar when dismissed.
This way, you maintain the functionality while adhering to the rules of hooks in React.