Say I have a table with sort data and I want to store it on a state (or even 3 separated states). Assume this state could be changed by the child. Is there anyway to do this without having 3 different useEffects, I would like to see if it is possible to achieve the same as below with only 1 use effect?
import React, { useState, useEffect } from "react";
function Table({ initialSortDirection, initialSortParam, initialSortEnabled }) {
const [currentSortData, setSortData] = useState({
sortDirection: initialSortDirection,
sortParam: initialSortParam,
hasSort: initialSortEnabled
});
useEffect(() => {
setSortData({ ...currentSortData, sortDirection: initialSortDirection });
}, [initialSortDirection]);
useEffect(() => {
setSortData({ ...currentSortData, sortParam: initialSortParam });
}, [initialSortParam]);
useEffect(() => {
setSortData({ ...currentSortData, hasSort: initialSortEnabled });
}, [initialSortEnabled]);
return (<SomeComponent onChangeSort={setSortData} />)
}
On a old school way I would probably use componentWillReceiveProps and just compare nextProps to see if they changed but now I am having difficult on finding a concise way to do it "at once" and only on change.
As a visual example consider the image below, you could change the sort either from clicking on the cell or from changing the "knobs".
EDIT 1
Assume that other things could affect the state and I do not want to override an updated state with an unchanged initial prop . I updated the code accordingly
EDIT 2 Added storybook picture
initialSortDirection,initialSortParam,initialSortEnabled) do always have a value?setSortData({ ...currentSortData, hasSort: initialSortEnabled });. You would only change thehasSortproperty. By the way, in this case, I would recommend the functional form ofsetState()to work with state that depends on the previous state:setSortData((prevState) => {return ({...prevState, hasSort: initialSortEnabled});}