Created
January 21, 2022 21:24
-
-
Save smikhalevski/a6a1b675a383981f2a67abcdb902c292 to your computer and use it in GitHub Desktop.
React inline functional component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {createElement, Fragment, isValidElement, ReactElement, ReactNode, useCallback} from 'react'; | |
export interface FcProps<P> { | |
render(props: P): ReactNode | null | void; | |
} | |
function Fc<P extends FcProps<P>>(props: P): ReactElement | null { | |
const v = useCallback(props.render, [])(props); | |
return v === undefined ? null : isValidElement(v) ? v : createElement(Fragment, null, v); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useEffect, useState} from 'react'; | |
import {Fc} from './Fc'; | |
let a = ( | |
<Fc render={() => { | |
const [count, setCount] = useState(1); | |
useEffect(() => { | |
const timeout = setInterval(() => setCount((count) => count + 1), 1_000); | |
return () => clearInterval(timeout); | |
}, []); | |
return count; | |
}}/> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment