Put operations out of useEffect?

Viewed 34

Am I allowed to put operation out of useEffect, is it good practice?

function BuyTicket(props: any) {
    
    useEffect(() => {
        //..
        }, [eventId, props.history]);
    
    // CODE HERE IS OK?
    const userNameLoggedIn = localStorage.getItem("userNameLoggedIn");
    if (buyTicketData) {
        if (buyTicketDataPasses.length === 0) {
            buyTicketDataPasses = Object.keys(buyTicketData.passes);
            buyTicketDataPasses.unshift("");
        }
        
    
    
      return (
          <div className="container">
      )
    }
}

export default withRouter(BuyTicket);
1 Answers

It's just a JavaScript function, so you're allowed to do that. However, side-effects are supposed to go in a useEffect hook, so it's not good practice.

Would you want to pull the username from local storage every single render? A component may render several times during a state change. Username doesn't seem like something that would change very often during the component's life, so fetch it once. Just retrieve it on mount like so:

useEffect(() => {
    // set in state vs retrieving each render
    setUsernameState(localStorage.getItem("userNameLoggedIn"))
}, [/* empty array means it runs only once */])
Related