React Native

What is the purpose of the useImperativeHandle hook in React Native?

Medium
5
Added
The useImperativeHandle hook is used to customize the instance value that is exposed to parent components when using ref forwarding.

Solution Code

React Native
-- Example Code --
import React, { useRef, forwardRef, useImperativeHandle } from "react";
import { View, Text, Button } from "react-native";

const FancyButton = forwardRef((props, ref) => {
  const localRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      localRef.current.focus();
    },
  }));

  return (
    <Button ref={localRef} title="Fancy Button" />
  );
});

const App = () => {
  const buttonRef = useRef();

  return (
    <View>
      <FancyButton ref={buttonRef} />
      <Button title="Focus Button" onPress={() => buttonRef.current.focus()} />
    </View>
  );
};

export default App;
Explanation
This code demonstrates how to use the useImperativeHandle hook to customize the exposed instance value.

Guided Hints

{'hint': 'Use useImperativeHandle to customize the instance value.'}
{'hint': 'It is used with ref forwarding.'}