Custom hooks in ReactNative

Sanjana Human In Tech
2 min readJan 1, 2024

Custom hooks in React are functions that allow you to reuse stateful logic in your components. Here’s an example of how you can write a custom hook programmatically:

// useCustomHook.js
import { useState, useEffect } from 'react';

const useCustomHook = (initialValue) => {
// State variable
const [value, setValue] = useState(initialValue);

// Effect to run some logic when the component mounts or when the value changes
useEffect(() => {
// Your custom logic here
console.log('Custom hook logic executed');

// Cleanup function (optional)
return () => {
console.log('Clean up custom hook logic');
};
}, [value]); // Dependency array, re-run effect when the value changes

// Function to update the value
const updateValue = (newValue) => {
setValue(newValue);
};

// Return whatever you want from the hook
return {
value,
updateValue,
};
};

export default useCustomHook;

Now, you can use this custom hook in your React components:

// ExampleComponent.js
import React from 'react';
import useCustomHook from './useCustomHook';

const ExampleComponent = () => {
// Using the custom hook
const { value, updateValue } = useCustomHook('initialValue');

return (
<div>
<p>Value: {value}</p>
<button onClick={() => updateValue('newValue')}>Update Value</button>
</div>
);
};

export default ExampleComponent;

In this example, useCustomHook is a custom hook that provides a state variable (value), a function to update that variable (updateValue), and includes some custom logic using the useEffect hook. The ExampleComponent then uses this custom hook to manage state and logic.

--

--

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.