I’m relatively new to React and currently learning about passing props to child components. I have a parent component called Counter and a child component called ChildComponent. My goal is to understand the performance and memory implications of different approaches for passing props to the child component.
Parent Component (Counter.js):
import React, { useEffect, useState } from 'react';
import ChildComponent from './CounterChild';
const Counter = () => {
const [count, setCount] = useState(10);
const getCount = () => {
console.count('count me');
return count * 2;
};
const increment = () => {
setCount(count + 1);
};
return (
<div>
<button onClick={increment}>Increment</button>
<ChildComponent count={getCount()} />
</div>
);
};
export default Counter;
Child Component (ChildComponent.js):
import React, { useEffect, useState } from 'react';
const ChildComponent = ({ count }) => {
const [count1, setCount1] = useState(count);
console.count('child count', count);
return (
<div>
<h3>Child Component</h3>
<p>Received count from parent: {count} </p>
<p>Count From Child Logic: {count1}</p>
</div>
);
};
export default ChildComponent;
In Approach 1, I’m passing the prop count to ChildComponent by calling a function getCount() within the parent component and passing its return value as the prop. This function is declared inside the parent component.
In Approach 2, I’m declaring the function getCount() outside the component and directly using it inside the parent component. I’m passing the function itself as the prop.
In Approach 3, I’m passing an arrow function as the prop to ChildComponent which returns count * 2.
<ChildComponent count={()=> count * 2} />
const ChildComponent = ({ count }) => {
const [count1, setCount1] = useState(count);
// rest of the code
In Approach 4, I’m directly passing the count state variable as the prop to ChildComponent and using the arrow functionn inside the useState.
<ChildComponent count={count} />
const ChildComponent = ({ count }) => {
const [count1, setCount1] = useState(()=>count*2);
I want to understand the performance and memory implications of each approach.
- Will declaring the function inside the parent component (Approach 1) cause memory allocation on each re-render?
- What about Approach 2 where the function is declared outside the component? Will it have any performance impact?
- Is there a recommended approach from a performance and memory standpoint ?
- Are there any React best practices for passing the data from parent to child?
I have seen React docs supporting the lazy initialization inside the useState() hook but still people are using functions inside the jsx.