Created
September 25, 2024 12:09
-
-
Save harilee1325/1788454adae0a5d0afb0cfcac24fa5f0 to your computer and use it in GitHub Desktop.
React Native Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. useState Hook | |
The useState Hook allows functional components to maintain internal state. This hook returns an array with two elements: | |
The current state value. | |
A function to update the state. | |
Example: | |
jsx | |
Copy code | |
import React, { useState } from 'react'; | |
import { View, Text, Button } from 'react-native'; | |
const Counter = () => { | |
// Initialize the state variable 'count' with a value of 0 | |
const [count, setCount] = useState(0); | |
return ( | |
<View> | |
<Text>Count: {count}</Text> | |
<Button title="Increment" onPress={() => setCount(count + 1)} /> | |
</View> | |
); | |
}; | |
In this example, useState(0) initializes the count state to 0, and setCount is the function that updates the count state when the button is pressed. | |
2. useEffect Hook | |
The useEffect Hook is used to handle side effects in functional components. Side effects can include fetching data, subscribing to services, or manually manipulating the DOM. It’s essentially a combination of lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components. | |
The useEffect function takes two arguments: | |
A callback function where the side effect logic resides. | |
An optional dependency array. The effect will re-run whenever any value in the dependency array changes. If the array is empty, the effect runs only once when the component mounts. | |
Example: | |
jsx | |
Copy code | |
import React, { useState, useEffect } from 'react'; | |
import { View, Text } from 'react-native'; | |
const DataFetcher = () => { | |
const [data, setData] = useState([]); | |
// Fetch data when the component mounts | |
useEffect(() => { | |
fetch('https://jsonplaceholder.typicode.com/posts') | |
.then((response) => response.json()) | |
.then((json) => setData(json)); | |
}, []); // Empty array ensures the effect runs only once (on mount) | |
return ( | |
<View> | |
{data.map((item) => ( | |
<Text key={item.id}>{item.title}</Text> | |
))} | |
</View> | |
); | |
}; | |
In this example, the useEffect Hook fetches data from an API when the component mounts, and updates the data state. | |
3. useContext Hook | |
The useContext Hook allows you to access context values in functional components. Context is used to pass data through the component tree without having to pass props down manually at every level. | |
Example: | |
jsx | |
Copy code | |
import React, { useContext } from 'react'; | |
import { View, Text } from 'react-native'; | |
// Create a Context | |
const ThemeContext = React.createContext('light'); | |
const ThemedComponent = () => { | |
const theme = useContext(ThemeContext); // Access the value of the context | |
return ( | |
<View> | |
<Text>The current theme is {theme}</Text> | |
</View> | |
); | |
}; | |
const App = () => { | |
return ( | |
<ThemeContext.Provider value="dark"> | |
<ThemedComponent /> | |
</ThemeContext.Provider> | |
); | |
}; | |
In this example, the ThemedComponent uses useContext to access the value of ThemeContext without needing to pass it down as props. | |
4. useReducer Hook | |
The useReducer Hook is an alternative to useState when dealing with more complex state logic. It works similarly to Redux, where a reducer function takes the current state and an action, then returns a new state. | |
Example: | |
jsx | |
Copy code | |
import React, { useReducer } from 'react'; | |
import { View, Text, Button } from 'react-native'; | |
// Reducer function | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'increment': | |
return { count: state.count + 1 }; | |
case 'decrement': | |
return { count: state.count - 1 }; | |
default: | |
return state; | |
} | |
}; | |
const Counter = () => { | |
// Use useReducer to manage state with a reducer function | |
const [state, dispatch] = useReducer(reducer, { count: 0 }); | |
return ( | |
<View> | |
<Text>Count: {state.count}</Text> | |
<Button title="Increment" onPress={() => dispatch({ type: 'increment' })} /> | |
<Button title="Decrement" onPress={() => dispatch({ type: 'decrement' })} /> | |
</View> | |
); | |
}; | |
In this example, useReducer manages the count state with actions like increment and decrement. | |
5. useRef Hook | |
The useRef Hook provides a way to access DOM elements or persist values without re-rendering the component. It can store a mutable value that persists across renders. | |
Example: | |
jsx | |
Copy code | |
import React, { useRef } from 'react'; | |
import { View, TextInput, Button } from 'react-native'; | |
const FocusInput = () => { | |
const inputRef = useRef(null); // Create a ref for the TextInput | |
return ( | |
<View> | |
<TextInput ref={inputRef} style={{ borderColor: 'gray', borderWidth: 1 }} /> | |
<Button title="Focus Input" onPress={() => inputRef.current.focus()} /> | |
</View> | |
); | |
}; | |
In this example, useRef is used to create a reference to a TextInput and trigger a focus event programmatically. | |
6. useMemo Hook | |
The useMemo Hook is used to optimize performance by memoizing expensive calculations. It caches the result of a function call and recomputes it only when its dependencies change. | |
Example: | |
jsx | |
Copy code | |
import React, { useState, useMemo } from 'react'; | |
import { View, Text, Button } from 'react-native'; | |
const ExpensiveCalculation = () => { | |
const [count, setCount] = useState(0); | |
const [toggle, setToggle] = useState(true); | |
// Memoize the expensive calculation | |
const expensiveValue = useMemo(() => { | |
console.log('Expensive calculation'); | |
return count * 2; | |
}, [count]); // Re-run only when 'count' changes | |
return ( | |
<View> | |
<Text>Expensive Value: {expensiveValue}</Text> | |
<Button title="Increment" onPress={() => setCount(count + 1)} /> | |
<Button title="Toggle" onPress={() => setToggle(!toggle)} /> | |
</View> | |
); | |
}; | |
In this example, the expensive calculation (count * 2) is only recomputed when count changes, avoiding unnecessary recalculations when other parts of the component update. | |
7. useCallback Hook | |
The useCallback Hook is used to memoize functions and prevent unnecessary re-creation of functions when a component re-renders. It’s useful when passing functions as props to child components. | |
Example: | |
jsx | |
Copy code | |
import React, { useState, useCallback } from 'react'; | |
import { View, Button } from 'react-native'; | |
const ChildComponent = React.memo(({ increment }) => { | |
return <Button title="Increment" onPress={increment} />; | |
}); | |
const ParentComponent = () => { | |
const [count, setCount] = useState(0); | |
const increment = useCallback(() => { | |
setCount((prevCount) => prevCount + 1); | |
}, []); // Memoized increment function | |
return ( | |
<View> | |
<ChildComponent increment={increment} /> | |
</View> | |
); | |
}; | |
Here, useCallback ensures that the increment function is only re-created when necessary, preventing unnecessary re-renders of the ChildComponent. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment