React, as you might be familiar, is a frontend web development library, and it is one of the most popular ones out there. Like other things in the fast-paced world of JavaScript, React has gone through its fair share of updates and changes through the years. None of those changes have been as revolutionary as the introduction of hooks in version 16.8.
Hooks introduced a new way of working with react. They removed a lot of boilerplate, got rid of having to deal with binding functions with ‘this’, and ultimately made the code a lot more clean, readable, and easy to work with. Hooks allow us to use React features and state without a class, and since react concepts are conceptually closer to functions rather than classes, this makes the life of the developers easier.
Since React Native is essentially just React for mobile apps, unsurprisingly, hooks are available here as well. While almost everyone is familiar with the useEffect and useState hooks, several other community-created hooks can make our code more readable, concise, and also reduce potential bugs and memory leaks.
A very common scenario in ReactJS and React Native is to create an event listener for an event, execute a function whenever the event occurs, and finally unsubscribe from the event and cleanup before unmounting the component. Handling several such asynchronous platform APIs can soon lead to a very cluttered codebase with multiple event listeners, multiple functions to be called from those event listeners, multiple cleanup functions, and ensuring that all of them are unsubscribed to prevent memory leaks and unintended side effects.
This is where hooks come to the rescue. Let’s take a look at an example:
import { useDimensions } from ‘@react-native-community/hooks’
const { width, height } = useDimensions().window
The above code imports a hook, useDimensions, and then gives us two variables, called height and width, which represent the height and width of the application’s window. This hook will not only get the dimensions but also sets up a listener that will change the dimensions if the user changes device orientation. We do not need to subscribe to the device’s orientation change event, and neither do we have to worry about updating the values in our code on this change. It’s all gracefully handled for us and tidily cleaned up when no longer required.
Another common use case for hooks is dealing with the keyboard:
import { useKeyboard } from ‘@react-native-community/hooks’
const keyboard = useKeyboard()
That’s all we need to do to use the keyboard. The keyboard const created above gives us properties such as the height of the keyboard and whether the keyboard is shown or not.
It’s immediately apparent that these hooks not only save time in development, they also improve readability and make our code more maintainable.
There are several such hooks available for use, check out the documentation here for a list of the available hooks from react-native-community: