Home > Software engineering >  useState not evaluating after history.push
useState not evaluating after history.push

Time:12-12

Are there any issues with history.push and useState?

Relevant part of my code

import { useParams, useLocation, useHistory } from 'react-router-dom'
const Component = () => {
    const history = useHistory()
    const { search } = useLocation()
    const searchParams = new URLSearchParams(search);
    const [name, setName] = useState(searchParams.get('name') || '' )
    
    const onClickButton = () => {
        history.push(`/items?page=1`) // New URL doesn't have name
    }
    useEffect(() => {
       console.log(name)
    }, [search])
    
    return (
      <button onClick={onClickButton}>Click</button>
    )

Now suppose my current URL is

/items?name=Apples

And then I have a button, when clicked, will route the user to

/items?page=1

However, for some reason,

const [name, setName] = useState(searchParams.get('name') || '' )

Evaluates to

Apple

Even though the useLocation.search() will only have

?page=1

CodePudding user response:

The value that's passed to useState is used as default value, it won't trigger new updates even there is new change, you should use combination with useEffect or use normal variable instead.

const [name, setName] = useState(searchParams.get('name') || '' )

useEffect(() => {
    setName(searchParams.get('name'));
}, [searchParams.get('name')])

or

const name = searchParams.get('name') || ''

CodePudding user response:

You're not setting the name state to any new value here - useState() takes an initial value as an argument, it won't set the state to that value for each render. So for example, when you initially set your name state, it will evaluate searchParams.get('name') and assign that value to name. On each subsequent render, however, only a call to setName will change the name state, it will not evaluate the initial value function argument again.

  • Related