is there anyway I can force re-render a component using ref?
maybe something like this:
const CustomComp=React.memo(React.forwardRef(({...props},ref)=>{
return(<View ref={ref} style={...}></View>);
}));
export default function App() {
const Mainref=useRef();
return(<View>
<Pressable onPress={()=>{Mainref.TriggerRender()}}></Pressable>
<CustomComp ref={Mainref}/>
</View>);
}
that way if there are multiple sibling components with different refs
you wouldn't have to re-render all of them just to re-render one
is such a thing possible? or is there something similar to it?
You can pass a callback to re-render the child component.
const CustomComp=React.memo(React.forwardRef(({...props},ref)=>{
const [toggle, setToggle] = React.useState(false);
function onUpdate() {
// will trigger re-render
setToggle(!toggle);
}
// set onUpdate on mount
React.useEffect(() => {
if (ref.current) ref.current.onUpdate = onUpdate;
});
return(<View ref={ref} style={...}></View>);
}));
export default function App() {
let Mainref=useRef();
return(<View>
<Pressable onPress={()=>{Mainref.current.onUpdate()}}></Pressable>
<CustomComp ref={Mainref}/>
</View>);
}
Better approach is to lift the state to a level higher in the component tree, or use a global state manager such as React context API in case the state does not belong in the App component.
const CustomComp=React.memo(React.forwardRef(({...props},ref)=>{
return(<View ref={ref} style={...}></View>);
}));
export default function App() {
let Mainref=useRef();
const [toggle, setToggle] = React.useState(false);
function onUpdate() {
// will trigger re-render on the whole view
setToggle(!toggle);
}
return(<View>
<Pressable onPress={onUpdate}></Pressable>
<CustomComp ref={Mainref}/>
</View>);
}