Hooks are introduced in React 16.8 and React Native 0.59. As stated from Facebook: “They let you use state and other React features without writing a class”. In other words, it extends functional components’ abilities to use state and side effects (such as fetching data from your backend API).

Pro tip: As Hooks coming into play, we should always use function components to build our apps whenever possible instead of class components. You could read more about them here and see the problem of class components with this here.

Let’s continue with the code from the previous part. Otherwise, you can clone git by the below command:

git clone -b make_hello_world_app https://github.com/thinhtran3588/react-native-starter-kit.git

Let's make changes to src/app.tsx and src/app.style.ts

app.tsx
app.style.ts

Now run your app. You'll see the button ‘Get your lucky color today’ on the screen. Click it then you'll get your lucky color.

Let’s take a look at that line:

const [color, setColor] = useState('');

useState is a Hook function that returns an array with 2 elements: a state and a function to update that state. Destructuring assignment is used to assign those values to 2 variables: color & setColor. The default value ‘’ is passed to useState so nothing is shown when the app is opened.

Pro tip: Always use Destructuring assignment whenever possible to make your code shorter and cleaner.

You will notice now that getRandomColor is placed outside the component. styles variable is the same (in another file). They're static so they don't need to be initialized each time the component is (re)rendered.

Pro tip: Bring static variables, functions outside the component is a way of optimizing the memory & performance since we only have to allocate memory & initialize them once.

Look at that line in the return statement:

<Text style={[styles.colorText, {color}]}>{color}</Text>

The style object is not only a JSON object but also can be an array of JSON objects and eventually are merged into a JSON object.

Pro tip: If your component has some dynamic styles, you should make use of styles array as above example. The first elements should be the default styles, and the last ones should be the dynamic styles.

Now I want another function to show randomized colors over time. Add those lines of code inside your component:

const [randomColor, setRandomColor] = useState('');useEffect(() => {    const changeColorInterval = setInterval(() => {        setRandomColor(getRandomColor());    }, 1000);    return () => {        clearInterval(changeColorInterval);    };}, []);

Next, add those to your return statement, inside the View component:

<Text>Random colors:</Text><Text style={[styles.colorText, {color: randomColor}]}>    {randomColor}</Text>

Your src/app.tsx should look like that:

app.tsx

Then save and switch to the emulators, you'll see those screens:

Screenshots

Let's take a look at the code. We have another state randomColor and use another type of Hooks: useEffect. useState is called directly in the component since it doesn't need to return any values. It has 2 parameters: the function which is executed after the component is rendered and an array of values that the effect depends on (states and/or props).

Pro tip: separate states if they're independent. Instead of using a big state object in a component, you should break it into smaller states. Ideally, those states are only primitive values or a simple JSON object (not nested one).

Note: always put the second parameter into useEffect even there is no dependency (it should be a blank array []). If not, the function inside useEfffect always is triggered unnecessarily (and wrongly) if the component is rerendered.

In the sample, we use useEffect to set up an interval so that the randomColor is updated per second. We also return a function to do the clean job (clear the interval) when the component is unmounted.

Please also note that useEfffect is used for ‘mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component’.

useState and useEffect are the most basic and also the ones we use most to build our applications. In fact, in this tutorial, you only need those 2 to build yours.

Congratulations! You’ve already had all the basic knowledge to create a React Native app.
You can read more about hooks here (other types of hooks and how to build your custom hooks). Besides, you may take a look at another concept called Context which is used to share ‘global' data inside your app. However, in this tutorial, we won't use it but use another awesome 3rd solution (rematch) to do that job.

You can also clone the sample here:

git clone -b understand_hooks https://github.com/thinhtran3588/react-native-starter-kit.git

Next: Setup VSCode with recommended extensions.

Prev: Understand React Native’s Architecture.

Back to Introduction.

--

--

Thinh Tran

Software developer. Interested in web/mobile application development with React, React Native, Typescript, Nodejs and AWS.