Why do we use curly braces in React function component's parameters

On line number 3 we have used curly braces in the function’s parameter
function newTask( { newtask,handleChange,handleSubmit } )

Anyone please give the reason why we have used these curly braces. I know it’s a silly question but I can’t remember why we used this.

Hello, and welcome to the forums!

It’s not a silly question at all. It’s using object destructuring in order to make working with the props for the component easier. You may be more familiar with destructuring outside of the function parameters, but they are very similar.

These will work the same way for this component:

export default function NewTask({ newTask, handleChange, handleSubmit }) {
  return (
    // original code omitted 
  );
}
export default function NewTask(props) {
  const { newTask, handleChange, handleSubmit } = props;
  return (
    // original code omitted since it's used the same way
  );
}
export default function NewTask(props) {
  const newTask = props.newTask;
  const handleChange = props.handleChange;
  const handleSubmit = props.handleSubmit;
  return (
    // original code omitted since it's used the same way
  );
}

and this is what the component would look like if we didn’t use object destructuring or assign the values from props to variables

export default function NewTask(props) {
  return (
    <form onSubmit={props.handleSubmit}>
      <input
        name="title"
        placeholder="New task"
        value={props.newTask.title || ""}
        onChange={props.handleChange}
      />
      {!props.newTask.title ? null : (
        <>
          <textarea
            name="description"
            placeholder="Details..."
            value={props.newTask.description || ""}
            onChange={props.handleChange}
          />
          <button type="submit">Add Task</button>
        </>
      )}
    </form>
  );
}

Notice that I didn’t omit the original code this time because changes had to be made to the rest of it in order to use the values from the object that was passed to the function.

1 Like