Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it best practise to set a default state then overwrite with useEffect if default state is potentially unreachable

I’m working with Nextjs and Next-Router, I have a side bar which indicates where you are in the application. The highlighted key on the sider is set by setting defaultSelectedKey which is a state like so:

    const [selectedMenuItem, setSelectedMenuItem] = useState(...);

It’s important this selected key is correct as otherwise it can indicate you’re in a different section of the application, specifically on refresh where the current state is lost.

I can get the state either by setting it is ‘1’ and then running a use effect that sets it again like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    useEffect((): void => {
        const item = items.find((item) => item.route === router.pathname)
        setSelectedMenuItem(item!.key)
    }, [])

or I can do it directly in the state initiation like so:

    const [selectedMenuItem, setSelectedMenuItem] = useState((items.find((item) => item.route === router.pathname))!.key);

Is there any benefits / drawbacks to either method? What is best practise in this scenario?

>Solution :

You can use either approach, but the drawback with setting the default state through the useEffect is that code inside useEffect will be executed on the first render, but the updated state will be set to selectedMenuItem only on the second render, so there will be some flash of the first state.

The correct approach is to use function as the argument of useState as this code will be executed only on the first render:

const [selectedMenuItem, setSelectedMenuItem] = useState(() => (items.find((item) => item.route === router.pathname))!.key);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading