0

I am trying to use the useMemo hooks in React js. According to the function we are sorting the array containing string in it. However when in returning the array back from the function it is just returning the first element of the array. Can you please help me understand what I am doing wrong in it.

import { useState } from "react";
import { useMemo } from "react";

export default function MemoExample2() {

  const [nameList, setNameList] = useState(['a', 'b', 'r', 'e']);

  const [sortedList] = useMemo(() => {
    console.log([...nameList].sort());
    return [...nameList].sort();


  }, [nameList]);

  function addLetter(e) {
    console.log()
    const letter = document.querySelector("#letter").value;

    setNameList([...nameList, letter]);
  }




  return <>
    <div>Unsorted: {nameList.join(' ,')}</div>
    <div>Sorted: {sortedList.join(',')}</div>
    <input type="text" id="letter" />
    <button onClick={addLetter}>Add Name</button>
  </>


}

The output should be a sorted array printed on HTML document.

  • 1
    You're destructuring the first element from the sorted array with `const [sortedList] = ...`, just use `const sortedList = ...` instead – Nick Parsons Nov 29 '22 at 10:40
  • See this for more info on destructuring assignment: [What is destructuring assignment and its uses?](https://stackoverflow.com/q/54605286) and the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) on it – Nick Parsons Nov 29 '22 at 10:42
  • Also, you should avoid using DOM methods like `document.querySelector("#letter")` when using React. Instead, you can create some state for your input element, and then update that state as it changes, then use that state when you click your button – Nick Parsons Nov 29 '22 at 10:45

1 Answers1

1

2 Issues with your code.

  1. As @Nick said you are using the variable as an array and from useMemo, you returning a single element not an array [].
  2. Also Don't use document.querySelector in React. You should be using useRef.

Following is the sample code which solves 2 issues and it works.

import { useMemo, useRef, useState } from "react";

export default function App() {
  const ref = useRef();
  const [nameList, setNameList] = useState(["a", "b", "r", "e"]);

  const sortedList = useMemo(() => {
    console.log([...nameList].sort());
    return [...nameList].sort();
  }, [nameList]);

  function addLetter(e) {
    const letter = ref.current.value;
    setNameList([...nameList, letter]);
  }

  return (
    <>
      <div>Unsorted: {nameList.join(", ")}</div>
      <div>Unsorted: {sortedList.join(", ")}</div>
      <input ref={ref} type="text" id="letter" />
      <button onClick={addLetter}>Add Name</button>
    </>
  );
}
Dhaval Gajjar
  • 2,508
  • 1
  • 2
  • 13