As setState
is async method in react. Is there any alternate to work with callback.
Note1 : I can use useEffect
as it cause to unlimited function call.
Note2 : Also I can't use function2
without reference as it's being used in many places.
const [state,setState] = useState([]);
const data = []; // data of 1000
const function1 = (name) => {
const tempState = data.filter(ele => ele.name == name);
setState(tempState);
function2(tempState[0])
}
const function2 = (element) => {
const tempState = state.filter(ele => ele.id == element.id);
setState(tempState);
}
Above code always returns []
. possible reason I can find is function2
has called before setState
. That is filtering empty array that's why I'm getting mpty array.
As mention in code if I use useEffect
then to call function2(state[0])
. But inside function2
we have setState
method call which makes re-render again & again.
is there any possibility where I can use callback method like this
setState(tempState,() => function2(state[0]) );