Skip to content

Instantly share code, notes, and snippets.

@matthewdavi
Last active June 28, 2019 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewdavi/5b4b9cf88b4b689152221d5ed6457bff to your computer and use it in GitHub Desktop.
Save matthewdavi/5b4b9cf88b4b689152221d5ed6457bff to your computer and use it in GitHub Desktop.
Recursive react component
/* I haven't seen anyone write about this, but I thought about it this morning in the shower and it works, why wouldn't it?
JSX is just sugar for function calls (React.createElement). */
const Fib: React.FC<{
start?: number;
end: number;
previous?: number[];
}> = ({ end, start = 2, previous = [1, 1] }) => {
const memo = previous.concat(
previous[previous.length - 1] + previous[previous.length - 2]
);
if (start >= end)
return (
<>
{memo.map((num, i) => (
<div key={i}>{num}</div>
))}
</>
);
return <Fib end={end} start={start + 1} previous={memo} />;
};
@matthewdavi
Copy link
Author

Here's a codesandbox link to demo https://codesandbox.io/s/recursive-react-8iuol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment