Why doesn't my state change when the category on useParams changes?

Viewed 745
 const { category } = useParams();
 const [sort, setSort] = useState(category);

This think is really driving me crazy - when i console the category, it is actually changing, but sort state doesn't..

2 Answers

You need to do some reading in order to understand how React Hooks work. There are many tutorials online - the React API documentation is even a good start:

What do we pass to useState as an argument? The only argument to the useState() Hook is the initial state.

From the React docs. Notice they say the argument is the initial state only.

When you do useState(X) - the value X is only used the first time the component is rendered. On subsequent renders, if and when X changes, and you want to use the new X, you must update the state value yourself via the set function returned by useState.

In your case, we can say that the state variable changes whenever category changes, so category is a dependency of the state variable. When you have a dependency of this kind, you know you need to use an effect, by way of the useEffect hook:

const { category } = useParams();

const [sort, setSort] = useState(category);

// This callback will run whenever the dependencies
// specified in the second argument change.
useEffect(() => {
  setSort(category)
}, [category]) // <= the dependencies

You are expecting whenever category changes, sort should also changes, if this is the goal, try this:

useEffect(() => setSort(category), [category]);

if you only want to change sort first time on initial render, try this:

useEffect(() => setSort(category), []);

For more info, see Using the Effect Hook - React

Related