React's useImperativeHandle with practical example | by ByteCode Pandit
Hi, all techies today we are going to discuss the react's important hook useImperativeHandle.
What it solved for me
When I was working on a react-native project, there was a situation when I have to toggle the modal view. So for that, I just took another boolean state in the parent component and changed it.
import React, { useState } from 'react';
import { Pressable, Text, View } from 'react-native';
export const ParentComponent = (props: any) => {
const [showModal, setShowModal] = useState<boolean>(false);
const toggleModal = (value: boolean) => {
setShowModal(value);
}
return <View>
<Pressable onPress={() => toggleModal(true)}><Text>Show Modal</Text></Pressable>
{showModal && <ModalComponent />}
</View>
}
But because as we know whenever we change the state of the component it gets rerender which I didn't want, and here the useImperativeHandle came into the picture.
React document says:
useImperativeHandlecustomizes the instance value that is exposed to parent components when usingref. As always, imperative code using refs should be avoided in most cases.useImperativeHandleshould be used withforwardRef
How to use useImperativeHandle in child component
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { Text, View } from 'react-native';
const ModalComponent = (props: any, ref: any) => {
const [showModal, setShowModal] = useState<boolean>(false);
const [count, setCount] = useState<number>(0);
useImperativeHandle(ref, () => ({
toggle: (value: boolean) => {
setShowModal(value);
},
countInc: () => {
setCount(count + 1);
}
}));
if(!showModal) {
return null
} else {
return <View><Text>Count: {count}</Text></View>
}
}
export default forwardRef(ModalComponent);
import React, { useRef } from 'react';
import { Pressable, Text, View } from 'react-native';
export const ParentComponent = (props: any) => {
const modalRef = useRef(null);
const toggleModal = (value: boolean) => {
modalRef.current.toggle(value);
}
const countInc = () => {
modalRef.current.countInc();
}
return <View>
<Pressable onPress={countInc}><Text>Increase Count</Text></Pressable>
<Pressable onPress={() => toggleModal(true)}><Text>Show Modal</Text></Pressable>
<ModalComponent ref={modalRef}/>
</View>
}
That's it! Hopefully, it helps you better understand how to use this weird hook.

Awesome post
ReplyDeleteUseful Post
ReplyDeletecan you pls suggest me how to use forwardRef with redux connect
ReplyDelete