React Native

How do you implement a custom hook in React Native?

Medium
6
Added
You can implement a custom hook in React Native by creating a function that uses other hooks and returns a value or an object.

Solution Code

React Native
-- Example Code --
import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";

const useCounter = (initialValue = 0) => {
  const [count, setCount] = useState(initialValue);

  useEffect(() => {
    console.log(`Count is now ${count}`);
  }, [count]);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return { count, increment, decrement };
};

const App = () => {
  const { count, increment, decrement } = useCounter(5);

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

export default App;
Explanation
This code demonstrates how to create and use a custom hook.

Guided Hints

{'hint': 'Custom hooks are functions that use other hooks.'}
{'hint': 'They can return values or objects.'}