I have a component with some different states: all the states are separate views of one object, and they are not mutually exclusive.
Imagine a class with a dozen of scholar: they all have characteristics that I describe with states: eye color, hair color, gender and so on.
So, I can select 'all the scholars with brown hair AND male' or 'all with blue eyes and female' and so on.
So I have all these states that act as filters.
But there is another state, say state1, which represent a specific scholar, say 'John Park' or 'Sarah Fawcett'.
When this filter is activated there is just one possible answer, and all the other filters vanish
const [specificPerson,setSpecificPerson]=useState(false);
const [hairColor,setHairColor]=useState(false);
const [eyeColor,setEyeColor]=useState(false);
const [gender,setGender] = useState(false);
const allScholars = [array of all scholars];
const [selectedScholars, setSelectedSCholars] = useState([]);
then I have 2 useEffect:
useEffect(() => {
setHairColor(false);
setEyeColor(false);
setGender(false);
}, [specificPerson] )
useEffect(() => {
set list = [];
if (hairColor || eyeColor || gender) {
list.add(allScholars.filter (byHairColor)
list.add(allScholars.filter (byEyeColor)
list.add(allScholars.filter (byGender)
} else {
list.add(specificPerson);
setSelectedScholars(list.unique);
}, [allScholars, selectedScholars, specificPerson, hairColor, eyeColor, gender, setSelectedScholars] )
return <>selectedScholars.map(each .....) </>
now, the current state of my application is as follow:
hairColor = brown
eyeColor = false
gender = false
specificPerson = false
All the sholars with brown hair are collected into the selectedScholars and then rendered.
Then, the event setSpecificPerson("John Doe") occurs.
"John Doe" should be rendered and all the other scholars should disappear because of the first useEffect.
What really happens is just another movie:
specificPersonspecificPerson, but hairColor is not yet changed and is still brown, because of the queue.specificPerson is not rendered.I hope this example be more realistic of the previous one.