Why doesn’t key change with useParams unless I also use useState?

TLDR; In trying to remount a child component, I can do this:

const {index} = useParams();
const [state, setState] = useState(index);

useEffect(() => { setState(index) }, [index]);

return <SomeComponentINeedToReMount key={state} />;

But not this:

const {index} = useParams();

return <SomeComponentINeedToReMount key={index} />;

Why?

Long version:

SomeComponentINeedToReMount has its own (somewhat complex) state, using useReducer. The initial state of SomeComponentINeedToReMount is based on index. So I want to render a new version of it when the index changes. This seems much simpler than putting logic in the child to reset the reducer on props change.

I find it odd that all other places that point to index ingest its changes just fine. It just seems that the key parameter, which I think is the only way to do what I’m trying to do, does not, and requires this extra piece of state to do it.

Source: React Router Questions

LEAVE A COMMENT