I am curious to know if the performance of a React app will be affected if we have multiple nested components and we pass a callback function to the lowest-level component and then the entire component tree is rendered from an event in the lowest-level component that triggers this callback.
If so, what are the best possible ways to tackle this?
Thanks.
CodePudding user response:
There are plenty of ways to pass data, but less so for functions.
Redux could be used, or useContext, or some other external solution like jotai.
Actually, the recommended official way is useContext: https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down
const TodosDispatch = React.createContext(null);
function TodosApp() {
// Note: `dispatch` won't change between re-renders
const [todos, dispatch] = useReducer(todosReducer);
return (
<TodosDispatch.Provider value={dispatch}>
<DeepTree todos={todos} />
</TodosDispatch.Provider>
);
}
function DeepChild(props) {
// If we want to perform an action, we can get dispatch from context.
const dispatch = useContext(TodosDispatch);
function handleClick() {
dispatch({ type: 'add', text: 'hello' });
}
return (
<button onClick={handleClick}>Add todo</button>
);
}
But frankly, passing a function several components down isn't so bad either.
It makes data dependencies more explicit and improves testability, although it's a bit verbose indeed. Do what you feel is more right. You can change your approach later (in this case) pretty easily.