Write better components using hooks

Table Component

The Solution — component + controller (with hooks!)

We separate the controlled component, which is just the view layer, from its state-manager, or ‘controller’ (yikes, I just used view-controller terminology :))

export const DataTable = ({ data, selection, sorting, setSelection, setSorting, ... })
export const useDataTableState = (...) => {
const [selection, setSelection] = useState(initialSelection);
const [sorting, setSorting] = useState(initialSorting);
...
}
return {
selection,
setSelection,
sorting,
setSorting,
...
}
import { DataTable, useDataTableState } from ‘data-table’;const MyComp = () => {
const dataTableState = useDataTableState();
return <DataTable {...dataTableState} data={ … }/>;
}
import { DataTable, useDataTableState } from ‘data-table’;const MyComp = () => {
const dataTableState = useDataTableState();
return (<div>
<DataTable {...dataTableState} data={ … }/>
<span>Selected { size(dataTableState.selection) } rows</span>
<button onClick={ dataTableState.setSelection({}) }>Clear selection</button>
</div>);
}
export const DataTable = ({ data, selection, sorting, setSelection, setSorting, ... }) => (
// this is the controlled component implementation
...
)
export const useDataTableState = (initialSelection = {}, initialSorting = null, ...) => {
// here we implement the state management logic
const [selection, setSelection] = useState(initialSelection);
const [sorting, setSorting] = useState(initialSorting);
...
return {
selection,
setSelection,
sorting,
setSorting,
...
}
}

--

--

http://adamklein.dev/ I write code, and speak about it

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store