Before implementing recursion in React Js we need to understand what recursion actually is.
What is Recursion ?
Recursion is the process in which a function calls itself several times until the base case in reached. Let's understand it with an example.
function count(n) {
if(n > 5) {
return;
}
n++;
}
count(1);
In the above code the count function is calling itself 5 times until the base case is reached which is (n>5).
Why use recursion in React ?
Recursion can help make the code more readable and modular. Let's see how with an example.
export const data = [
{
name: "Parent",
children: [
{
name: "Child-1",
},
],
},
{
name: "Parent",
children: [
{
name: "Sub-Parent",
children: [
{
name: "Child",
children: [
{
name: "Sub-Parent",
},
],
},
],
},
{
name: "Child",
},
],
},
];
The above is an nested json object. Suppose we have to render each children for that we need to map through each parent and check whether it has an children or not.
const NonRecursiveComp = ({data}) => {
return (
<div>
{data.map((parent) => {
return (
<div key={parent.name}>
<span>{parent.name}</span>
{parent.children.map((child) => {
return (
<div key={child.name} style={{ paddingLeft: "20px" }}>
<span>{child.name}</span>
{child.children !== null && child.children !== undefined &&
child.children.map((subChild) => {
return (
<div
key={subChild.name}
style={{ paddingLeft: "20px" }}
>
<span>{subChild.name}</span>
{subChild.children &&
subChild.children.map((subChild) => {
return (
<div
key={subChild.name}
style={{ paddingLeft: "20px" }}
>
<span>{subChild.name}</span>
</div>
);
})}
</div>
);
})}
</div>
);
})}
</div>
);
})}
</div>
)
}
In the above code we are using map function to render each child element. However the code is getting repeated for each nested data. If the nesting gets more complex the code will be much more longer which will make it difficult to read and maintain. To solve this problem we will use a recursive component to render the data.
Let's see how recursive component can make the above react code simpler with an example.
const RecursiveComp = ({data}) => {
return (
<div >
{data.map((parent) => {
return (
<div key={parent.name}>
{parent.name && <div>{parent.name}</div>}
<div>
{parent.children !==null && parent.children !== undefined && <RecursiveComp data={parent.children} />}
</div>
</div>
);
})}
</div>
);
}
In the above code we are rendering the component till the base case is reached which is parent.children !==null && parent.children !== undefined. As we can see the code is now much simpler and readable.
Conclusion
Recursion is used to break down a problem into simpler parts and can be used for variety of problems. Recursion uses stack memory and is slower than looping so it might not always be the most efficient way to solve a problem. So it is important to figure out if recursion is the right approach for solving a problem before implementing it in your react code base.
Top comments (1)
Good Explanation!