Home > Software engineering >  Is there any hooks method in ReactJS like this.setState() in class components?
Is there any hooks method in ReactJS like this.setState() in class components?

Time:06-06

I want to set multiple states and call the useEffect function at once. Here's some code for better understanding.

const [activePage, setActivePage] = useState(1);
const [skip, setSkip] = useState(0);
const [limit, setLimit] = useState(10);

const getUserList = ()=>{
    // do something
}

useEffect(() => {
        getUserList();
}, [activePage, skip, limit]);

Here you can see I have three dependencies. setting all dependencies calls the getUserList() three times. all three dependencies are independent. I want to call the getUserList() only once when I need to change all three states, similar to this.setState() in class components like:

this.setState({
    activePage: //new value,
    skip: // new value,
    limit: // new value
},()=>getUserList())

Can someone please let me know if there is any method to achieve this?

CodePudding user response:

This might not be the best solution but I think it should work. I imagine that when the state is changing three times at once, it's a special case, so you could create another state that would store a boolean that would be set to true in the case that it does happen. Then, the useEffect could be set for that boolean instead of all three states.

Special case where all 3 states are being updated:

setActivePage()
setSkip()
setLimit()
setAllChanged(true)

...
useEffect(() => {
    getUserList();
}, [allChanged])

CodePudding user response:

For your example, maybe immer.js will solve it better as your intended.

import produce from 'immer'

function FooComponent() {
  const [state, setState] = useState({
    activePage: 1,
    skip: 0,
    limit: 10
  })

  const getUserList = () => {}

  // use immer to assign `payload` to `state`
  const changeState = (payload) => {
    setState(produce(draft => {
      Objest.keys(payload).forEach(key => {
        draft.key = payload.key
      })
    }))
  }

  changeState({
    activePage: 2
  })

  useEffect(() => {
    getUserList();
  }, [state.activePage, state.skip, state.limit]);

  return (< />)
}
  • Related