Search code examples
reactjsrefactoringencapsulationreact-component

In React, how to encapsulate logic in a Todo component?


In a Todo app made with React, like this one, we have a function toggleTaskCompleted in the App component which gets passed as a prop to each Todo component. This function can then be called in the Todo component when a button is clicked resp. a checkbox is toggled.

I wonder if we can move this logic entirely to the Todo component. For example, this is possible in Svelte and Vue. In Vue, we create a ref for the list (and in Svelte, a regular variable), loop through it to list all todos and pass the respective todo as a prop. When we change the todo in the Todo component (for example, mark it as complete), this change is automatically also seen by the parent App component. (Meanwhile, the approach by passing a function as a prop is also possible in Svelte and Vue.)

I prefer this approach much more, it is more encapsulated, and we have to write less code. So I wonder if we can do the same in React.

Edit. Actually, the list is updated in the App component. However, this does not effect a rerender, and also useEffect, depending on the list, won't notice this change. So my question is basically how to inform the component about this change (without writing too much code or even using external state mangement).


Solution

  • I guess it would be better to use React Context in this case because you'll need to applay the state and the logic for your Todos in many components (like a navbar to track number of todos ...) . In this case React Context is a way to manage state globally. So it allow your components to access some global data (In your case your todos and the function toggleTaskCompleted ) and and re-render when that global data is changed . this is a simple Demo how to use it