Frontend
Back to frontend track
Deprecated

Solution

React Hooks: useState - 1

This question revolves around the most frequently used hook in React development. Your task is to implement the logic for managing tasks - including storing, adding, and deleting them within a local state variable.

Walkthrough

Compare with the solution.

Keep the explanation and implementation side by side.

Hooks: useState-1 | React Coding | Easy Practice Question | Frontend Hire

Watch alongside the notes.

Open video

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:

  1. The current value of the state
  2. A function to update the state
App.jsx
const tasks = [{ id: 1, taskName: 'First Task' }];
const [tasks, setTasks] = React.useState([{ id: 1, taskName: 'First Task' }]);

Next, we will wire up the addTask function:

App.jsx
const addTask = (task) => {
  // Write the logic
  const trimmedTask = task.trim();
 
  if (!trimmedTask) {
    return;
  }
 
  const newTask = {
    id: Math.random().toString(36).substr(2, 9),
    taskName: trimmedTask,
  };
 
  setTasks([...tasks, newTask]);
};

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.

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:

App.jsx
const deleteTask = (id) => {
  // Write the logic
  setTasks(tasks.filter((task) => task.id !== id));
};

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.

Bonus Task

How do we add a clear all tasks feature?

App.jsx
const clearAllTasks = () => {
  setTasks([]);
};

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.

App.jsx
<button
  onClick={clearAllTasks}
  className="border border-red-500 bg-red-500 p-2 text-white"
>
  Clear All
</button>