Related to
- How can I avoid unnecessary re rendering of an HOC component, when the parameter component renders in ReactJS with react router
- HOC inside react hook, causes infinite rerenders (solves initial problem, but does not handle a specific case with the forwardRef)
- ref from React.forwardRef is null but for HOC specifically and functional components
Given an app that's implemented as follows which triggers a state change every second:
export default function App() {
const [username, setUsername] = useState('');
const [now, setNow] = useState(format(Date.now(), 'PPPPpppp'));
useEffect(() => {
const c = setInterval(
() => setNow(format(Date.now(), 'PPPPpppp')),
1000
);
return () => clearInterval(c);
}, []);
return (
<View style={styles.container}>
<MyView>
<TextInput
placeholder="Username"
defaultValue={username}
onChangeText={setUsername}
/>
</MyView>
<Text>{now}</Text>
</View>
);
}
Given a simple
function MyView(props) {
return createElement(View, props);
}
The text input field does not lose focus when clicked
Now if I wrap it in an HOC with a useCallback to prevents infinite rerenders causing focus lost:
function withNothing(WrappedComponent) {
return useCallback((props) => <WrappedComponent {...props} />, [])
}
function MyView(props) {
return createElement(withNothing(View), props);
}
Now the last bit was to allow forwarding refs, but this is the part I couldn't get working.
My attempts so far https://snack.expo.dev/@trajano/hoc-and-rerender