1
function App() {
  const [input, setInput] = useState("");
  const [tasks, setTasks] = useState([]);

  function handleChange(event) {
    const value = event.target.value;
    setInput(value);
  }

  function handleClick() {
    setTasks([...tasks, input]);
    setInput("");
  }

  return (
    <div className="container">
      <div className="heading">
        <h1>To-Do List</h1>
      </div>
      <div className="form">
        <input type="text" value={input} onChange={handleChange} />
        <button type="submit" onClick={handleClick}>
          <span>Add</span>
        </button>
      </div>
      <div>
        <ul>
          {tasks.map((task) => {
            return <li>{task}</li>;
          })}
        </ul>
      </div>
    </div>
  );
}

Comparing option 1:

  function handleClick() {
    setTasks([...tasks, input]);
    setInput("");
  }

with option 2:

  function handleClick() {
    setTasks((prevValue) => [...prevValue, input]);
    setInput("");
  }

What are the implications of using calling the current state of tasks as opposed to option 2 in which prevValue is used to manage the complex state of tasks?

Both seem to work similarly in terms of functionality, but I understand from tutorial that option 2 preferable. Hence, I would like to understand what can happen if I don't use option 2?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
chu-js
  • 181
  • 7
  • 1
    The tutorial is wrong, option 1 is just fine. The callback version (option 2) is only needed if you have set a state value previously, and you want to set *the same state* again but the component hasn't re-rendered yet, and you want to use the value that was just set in the calculation for the new state. – CertainPerformance Sep 20 '22 at 04:40
  • Thanks, @CertainPerformance. What is a use case in which you have set a state value, but the component hasn't been re-rendered yet? Will it be within ```setTasks()```, or could there be a separate function? – chu-js Sep 20 '22 at 04:47
  • 1
    It would be if you had another call to `setTasks` ultimately inside the same handler somewhere. – CertainPerformance Sep 20 '22 at 04:49

0 Answers0