Solution
Use the useState hook
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
This is the stuff that you would do a lot in a CRUD application.
First, we will update the tasks
variable to use state, which in React is done with the useState
hook.
useState
returns an array with two items:
- The current value of the state
- A function to update the state
Next, we will wire up the addTask
function:
We check if the task is empty before we add it. If it is empty, we do not add the task and return. Otherwise, we create a new task object with a unique ID and the trimmed task name.
Unique IDs are usually created by a database. This random string method works for an interview setting, but do let the interviewer know that this is not the best way to generate unique IDs.
But why do we need to have a unique ID? Why not just use the index as the ID? Well, we can use the index as the ID if we want. But that would not help React understand which item in the list is being changed.
Then we use the setTasks
function to update the tasks
state with the new task. We use the spread operator to create a new array with the new task added.
Finally, we can wire up the deleteTask
function:
We filter the tasks
array to remove the task with the matching ID and create a new array without the deleted task. Then we use the setTasks
function to update the tasks
state with the new array.
If you are new to React, you might be tempted to push or splice on the array. Never do that in React with state variables.
One of the fundamental rules of React is to not modify the state directly. Always work with a copy of the state.
Bonus Task
How do we add a clear all
tasks feature?
We use the setTasks
function to update the tasks
state with an empty array to clear all tasks.
Next, we just have to link the function to a UI element. We will create a button that calls the clearAllTasks
function with some basic styling.
GreatFrontEnd has better questions!
We don't create questions because GreatFrontEnd already has the best possible library of questions and we recommend the same to our community.
Last updated on