I have a View
and Column
components. I use registerColumn
method to store column refs
in the View
context:
const [columns, setColumns] = useState([]);
const registerColumn = (node) => {
const column = {
someUniqueId: Math.random(),
node,
// more props
};
setColumns(prev => [...prev, column])
}
const context = {
columns,
registerColumn
}
<ViewContext.Provider values={context}>
<View>
<Column/>
<Column/>
<Column/>
</View>
<View>
<Table/>
</View>
</ViewContext.Provider>
Where I'm getting really confused is the Column
component. Whenever I try to register the column and get the updated length afterwards, it's not being updated on time, because setState
works asynchronously:
const {columns, registerColumn} = useContext(ViewContext);
const ref = useRef(null);
useEffect(() => {
registerColumn(ref.current);
// Here is where updated column length but it keeps saying it's 0 length
console.log(`Hello from column number ${columns.length}`);
}, []);
[...]
Docs are saying, that I can make use of the useEffect
with the columns
as the dependency and have the updated length on next render. However, I need to consume updated state right after registerColumn
is invoked - using another useEffect
will basically mean breaking execution context and the need to delay the task, plus possibly introduce other callbacks just to get around this.
I'm new to React but I'm pretty sure there are other possibilities to get around this, so any help will be greatly appreciated.