Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Once for Multiple set States using useState hook in React

Is there a way to refresh / render a function component once after updating multiple states?

For example:

const [first, setFirst] = useState(false);
const [second, setSecond] = useState(false);

when called ...

...
setFirst(true);
setSecond(true);

... then the component will refresh twice. Is it possible to set both and refresh (or render) only once?


1 Answers

You can use your states as an object and set them in one instead of separete states like

const [exampleState, setExampleState] = useState(
  {fields: {
        fieldOne: false,
        fieldTwo: false
        }
   })

You can set in this way

    setExampleState({...exampleState, fields: {
        fieldOne: true,
        fieldTwo: true
        },
   })
like image 156
Evren Avatar answered May 28 '26 13:05

Evren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!