Adrian Garcia Estaun
8 Dec 2022
•
3 min read
These last months I have seen that many people from my team were a bit confused about how the hooks work in our React Native application. In this post I’m going to answer some basic questions about them and I will show some examples to make it clearer.
A hook is a simple function that allows you to access the React Framework. That means that we get access to another hooks, for example useState, useEffect, useLayoutEffect, useMemo, useCallback, useImperativeHandle, etc… You might want to check all the hooks that React provide us. Check them out here.
No. But I really encourage you to try them if you haven’t done it yet. They will open up a range of possibilities, improving your React or React Native application, avoiding duplications, and making your code cleaner, more readable and organized.
The most important things that you need to be clear about are these:
I know, I know… we are developers and we need examples to see if we are really interested on implementig this. Let’s see a basic example.
import { useEffect, useState } from 'react';
import { Text } from 'react-native';
// Functional component.
const BasicTimer = () => {
const [seconds, setSeconds] = useState(0); // First hook.
// Second hook.
useEffect(() => {
setTimeout(addSecond, 1000);
});
const addSecond = () => {
setSeconds(seconds + 1);
};
return <Text>{`Seconds elapsed ${seconds}`}</Text>;
};
export default BasicTimer;
Here you can see a small functional component that prints the seconds elapsed since the component was mounted the first time.
The first hook is the useState hook, and it help us to keep the seconds elapsed in memory during the lifecycle of the component. This is the way it works:
Remember, useState is asynchronous. That means that if you check the value (seconds) just one line below the line that updates the value (setSeconds) the value will be the same as you had before calling the setSeconds function.
// Replace addSecond by this function to see that useState is asynchronous.
const addSecond = () => {
console.log('Seconds elapsed before calling setSeconds:', seconds);
setSeconds(seconds + 1);
console.log('Seconds elapsed after calling setSeconds:', seconds);
}
Let’s move forward with the useEffect hook. This hook helps us to call a function every time that React renders the component. This is the way it works:
// You can pass the function you want to call.
useEffect(myCallback);
const myCallback = () => {
setTimeout(addSecond, 1000);
}
But you don’t pass any second parameter
The second parameter is optional, and it works this way:
useEffect(() => console.log('Hello World!'), []);
useEffect(() => console.log('Hello World!', Date.now()));
const [time, setTime] = useState(Date.now());
useEffect(() => console.log('Hello World!', time), [time]);
Try to update the time variable calling setTime(Date.now()) inside the useEffect. You will create an infinite loop.
Hope you enjoyed the post.
Made with ❤️ for those who want to learn and teach.
Adrian Garcia Estaun
Whenever I encounter a new challenge, I make sure to learn about it so I can deliver the best results. Keeping up with the latest in technology is not just important for my professional growth, but also because I'm genuinely interested in it.
See other articles by Adrian
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!