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: 

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef


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);


How to use in the parent component

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>

}

So as you can see in the code, now we can easily change the child component state using the instance in the parent, because of this hack we don't need to change the parent's state and that's how we save the rendering.


That's it! Hopefully, it helps you better understand how to use this weird hook.


Comments

Post a Comment

Popular posts from this blog

Real-Life Use-Cases for useCallback and useMemo

Understand NgModule in 15 mins | by Bytecode Pandit