I am new to hooks. So this might be easy yet I have no idea how to solve:
I have a function like this which takes two arrays columns
and data
. and those data should be memoized or else it does not work. (recommended by react-table guys)
function ReactTable(props) {
const columns = React.useMemo(() => props.columns, [])
const data = React.useMemo(() => props.data, [])
return <Table columns={columns} data={data} />
}
this works fine but when the props change (say an item is added or removed from data array), the React.useMemo won't send the updated data to the Table component. How can I resolve this :(
This is exactly what the dependency array in hooks is for. You can define variables that 'trigger' the change on hooks. In your case this would mean that you would need to change your code to the following:
function ReactTable(props) {
const columns = React.useMemo(() => props.columns, [props.columns]);
const data = React.useMemo(() => props.data, [props.data]);
return <Table columns={columns} data={data} />
}
This means, whenever props.columns
changes, the columns
variable is updated and the same for props.data
and data
.