DEV Community

Chandra Prakash Tiwari
Chandra Prakash Tiwari

Posted on

Set a callback to setState(useState) in React funtional Component

It is hard sometime to call something after updating the state using useState hook in functional component in React.

Here is a simple trick:

  1. Define State using UseState
const [filterObj, setFilterObj] = useState({});
  1. Set State first
 // when props updates please update the state.
  useEffect(() => {
      setFilterObj({ ...props.something});
  }, [props.something]);
  1. 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]) 

Discussion (4)

Collapse
dance2die profile image
Sung M. Kim • Edited on

Thank you for sharing this trick, Chandra.

This was definitely asked a lot on StackOverflow, as setState provides a callback, but setting states using useState hooks' updator functions don't provide the same functionality.

Collapse
thejajibhee profile image
JAJI ⚡️⚡️ || BHEE INC.

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 ]);

Collapse
chandra profile image
Chandra Prakash Tiwari Author

Actually, this is an alternate solution for calling something after setting the state in a functional component. You can use useEffect() more than once.

Collapse
smarth19 profile image
Samarth Mittal

Thanks for the Solution. I needed this badly