It is hard sometime to call something after updating the state using useState hook in functional component in React.
Here is a simple trick:
- Define State using UseState
const [filterObj, setFilterObj] = useState({});
- Set State first
// when props updates please update the state.
useEffect(() => {
setFilterObj({ ...props.something});
}, [props.something]);
- UseEffect to call the function which you want to call after the setState.
// on state change call this event
useEffect(() => {
fetchData(currentPage); // this is a fuction which calls api
}, [filterObj])
Latest comments (4)
Thanks for the Solution. I needed this badly
Hi Prakash, so are you saying we write two effects or use one effect for both the setting of state and calling API?
useEffect(() => {
setFilterObj({ ...props.something});
}, [props.something]);
useEffect(() => {
fetchData(currentPage);
}, [filterObj])
OR
useEffect(() => {
setFilterObj({ ...props.something});
fetchData(currentPage);
}, [props.something, filterObj ]);
Actually, this is an alternate solution for calling something after setting the state in a functional component. You can use useEffect() more than once.
Thank you for sharing this trick, Chandra.
This was definitely asked a lot on StackOverflow, as
setState
provides a callback, but setting states usinguseState
hooks' updator functions don't provide the same functionality.