Hooks — useEffect, useContext, useRef, useCallback, and useMemo in ReactNative.

Sanjana Human In Tech
4 min readDec 31, 2023
React Hooks

React is a popular JavaScript framework for building web and mobile applications. One of the key features of React is its ability to manage state and update the user interface in response to changes in state.

In this blog post, we will explore how to use some of React’s most powerful hooks: useEffect, useContext, useRef, useCallback, and useMemo.

useEffect

The useEffect hook allows you to run side effects in a functional component. Side effects include things like fetching data from an API, updating the document title, or setting up and cleaning up event listeners.

Here’s an example of how to use useEffect to fetch data from an API:

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

function MyComponent() {
const [data, setData] = useState([]);

useEffect(() => {
fetchData();
}, []);

const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error(error);
}
};

return (
<View>
{data.map(item => (
<View key={item.id}>
<Text>{item.name}</Text>
</View>
))}
</View>
);
}

export default MyComponent;

When you provide an empty dependency array ([]) as the second argument to useEffect, it means that the effect will only run once, after the initial render.

This is commonly used for scenarios where you want to act only when the component mounts and not on subsequent renders.

Unmount the data in the functional component described as below :

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

function MyComponent() {
const [data, setData] = useState([]);

useEffect(() => {
// This code runs after the initial render

fetchData();

// Specify a cleanup function to be called when the component is about to unmount
return () => {
// Cleanup code goes here
// For example, you can cancel subscriptions, clear intervals, or perform other cleanup tasks
};
}, []); // The empty dependency array means this effect runs once after the initial render

const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error(error);
}
};

return (
<View>
{data.map(item => (
<View key={item.id}>
<Text>{item.name}</Text>
</View>
))}
</View>
);
}

export default MyComponent;

useContext

The useContext hook is used to consume values from the React context. It allows functional components to subscribe to a context and read its current value.

import React, { useContext } from 'react';
import { View, Text, Button } from 'react-native';

// Create a context
const MyContext = React.createContext();

// Create a context provider
const MyContextProvider = ({ children }) => {
const contextValue = "Hello from Context!";

return (
<MyContext.Provider value={contextValue}>
{children}
</MyContext.Provider>
);
};

// Component consuming the context
function MyComponent() {
// Use the useContext hook to access the context value
const contextValue = useContext(MyContext);

return (
<View>
<Text>{contextValue}</Text>
</View>
);
}

// Wrap the component with the context provider
function App() {
return (
<MyContextProvider>
<MyComponent />
</MyContextProvider>
);
}

export default App;

We create a context using React.createContext(). This creates a context object that has a Provider and a Consumer. We create a MyContextProvider component that serves as the provider for the context. It wraps its children with the MyContext.Provider component, providing a value prop that represents the data you want to share.

useRef

useRef is often used to access and interact with a child component , store mutable values, or manage focus in input elements.

import React, { useRef, useEffect } from 'react';
import { View, TextInput, Button } from 'react-native';

function MyComponent() {
// Creating a ref for a TextInput element
const inputRef = useRef();

useEffect(() => {
// Focus the input field when the component mounts
inputRef.current.focus();
}, []);

const handleButtonClick = () => {
// Access the current value of the input field using the ref
alert(`Input value: ${inputRef.current.value}`);
};

return (
<View>
<TextInput
ref={inputRef}
placeholder="Type something"
style={{ height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 10 }}
/>
<Button title="Alert Input Value" onPress={handleButtonClick} />
</View>
);
}

export default MyComponent;

useCallback

In React Native, the useCallback hook is used to memoize functions and prevent unnecessary re-renders, especially when passing functions as props to child components.

import React, { useState, useCallback } from 'react';
import { View, Text, Button } from 'react-native';

function MyComponent() {
const [count, setCount] = useState(0);

// Using useCallback to memoize the increment function
const increment = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []);

return (
<View>
<Text>{count}</Text>
<Button title="Increment" onPress={increment} />
</View>
);
}

export default MyComponent;

useMemo

In React Native, theuseMemo hook is used to memoize values, preventing unnecessary recalculations of those values during re-renders. This can be useful for optimizing performance by avoiding redundant computations.

import React, { useState, useMemo } from 'react';
import { View, Text, Button } from 'react-native';

function MyComponent() {
const [count, setCount] = useState(0);

// Using useMemo to memoize the result of an expensive calculation
const expensiveResult = useMemo(() => {
console.log('Calculating expensive result...');
// Simulating an expensive calculation
return count * 2;
}, [count]);

return (
<View>
<Text>Count: {count}</Text>
<Text>Expensive Result: {expensiveResult}</Text>
<Button title="Increment" onPress={() => setCount(prevCount => prevCount + 1)} />
</View>
);
}

export default MyComponent;

Thank you for reading this article! Don’t forget to clap.

If you have any queries related to ReactNative, I’m always happy to help you. You can reach me on LinkedIn and Gmail.

--

--

Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.