0

I'm a little bit confused how the call by reference/value would work between React component.

I have a component which pass its data to a Table component, in which the Table component will store the passed data for sorting purpose.

function User(){
  const [userList, setUserList] = useState([])
  //fetch and update userList
   ...

  function renderBody(){
     return userList.map(user=> 
        <tr>
           <td>{user.name}</td>
        </tr>
    )
  }

  return <Table data={userList} renderBody={renderBody} />
}

function Table({data, renderBody}){
  const [cache, setCache] = useState([])

  useEffect(()=>{
    if(data){
        setCache(data)
    }
  },[data])

  function sortOrder(){
    //using cache data and perform sorting
    const temp = cache.sort((x, y) => String(x[id]).localeCompare(y[id], 'en', { numeric: true }))
    setCache(temp)
  }
  
  return <table>{renderbody()}</table>

In my case, I forget to use the cache data to render the body of table. However, the sorting function still work! Even I only sorting the cache data, the original data (here the userList) is also sorted.

My Questions are:

  1. Is it work because of something like call by reference?

  2. Should I keep using this way to sort and render the data? Or it is better to let the render function use the cache data instead?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Carter
  • 1
  • 1
  • 1
    1) Yes. 2) That's subjective – Phil Mar 08 '23 at 05:58
  • I see. Thanks for you reply. I was wondering whether if it may be somthing difference when using the state in React. Seems like the concept are same. – Carter Mar 08 '23 at 07:25

0 Answers0