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:
Is it work because of something like call by reference?
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?