🎣 Using React Hooks in React Native
Problem
React Hooks will ship as part of React Native 0.59. If you are interested in using Hooks before then, see my comment below. Original issue: --- - [x] Review the documentation: https://facebook.github.io/react-native - [x] Search for existing issues: https://github.com/facebook/react-native/issues - [x] Use the latest React Native release: https://github.com/facebook/react-native/releases Environment [skip envinfo] OS: Windows 10 Node: 10.11.0 Yarn: Not Found npm: 6.4.1 Watchman: Not Found Xcode: N/A Android Studio: Version 3.2.0.0 AI-181.5540.7.32.5056338 Packages: (wanted => installed) react: 16.7.0-alpha.0 => 16.7.0-alpha.0 react-native: https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz => 0.55.4 expo: 2.2.0 Description When using React Hooks like `useState` within a function component, I get the following error message. > hooks can only be called inside the body of a function component [code block]
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Upgrade React Native to Support Hooks
The error occurs because React Hooks are only available in React versions that support them, specifically React 16.8.0 and above. The current React Native version (0.55.4) does not support Hooks as it is based on an earlier version of React. Therefore, attempting to use Hooks in a function component results in the error message: 'hooks can only be called inside the body of a function component'.
Awaiting Verification
Be the first to verify this fix
- 1
Upgrade React Native
Upgrade your React Native version to at least 0.59 or higher to ensure compatibility with React Hooks.
bashnpm install --save react-native@0.59.0 - 2
Upgrade React
Ensure that your React version is updated to at least 16.8.0, as this version introduces support for Hooks.
bashnpm install --save react@16.8.0 - 3
Verify Package Versions
Check your package.json file to confirm that both React and React Native versions are correctly updated.
bashcat package.json | grep 'react\|react-native' - 4
Test Function Component with Hooks
Create a simple function component that uses Hooks to verify that the setup is correct and that no errors occur.
javascriptconst MyComponent = () => { const [count, setCount] = useState(0); return <Text>{count}</Text>; }; - 5
Run the Application
Run your React Native application to ensure that it builds successfully and that the Hooks functionality works without errors.
bashreact-native run-android
Validation
To confirm the fix worked, ensure that the application runs without the previous error message when using Hooks in your function components. Additionally, check that the updated versions of React and React Native are reflected in your package.json.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep