You might find a context helpful at this point.A React Context allows defined data to be shared across components.
In your case you could implement it as follows
import { createContext } from 'react';
const ContactContext = createContext();
export default ContactContext;
in your root component you must then create the context provider
import ContactContext from './ContactContext';
function MyApp({ Component, pageProps }) {
const [contactName, setContactName] = useState(null);
return (
<ContactContext.Provider value={{ contactName, setContactName }}>
<Component {...pageProps} />
</ContactContext.Provider>
);
}
export default MyApp;
at this point we have defined the state contactName and pass the value and the set function to the created context.
Each component can now set the state of the MyApp component.
in the area of your navigation, you would then have to set the context accordingly. You can then access the corresponding function as well as the value itself via the useContext hook
import { useContext } from 'react';
import { useRouter } from 'next/router';
import ContactContext from './ContactContext';
function YourComponent({ contact }) {
const { setContactName } = useContext(ContactContext);
const router = useRouter();
const handleClick = (e) => {
e.preventDefault();
setContactName(contact.name);
router.push(`${routes.accountShow(contact.number)}/contacts`);
};
return (
<a
className={styles.summaryLink}
href={`${routes.accountShow(contact.number)}/contacts`}
onClick={handleClick}
>
</a>
);
}
The display component can also read the values via the useContext hook and then display the data accordingly.
import { useContext } from 'react';
import ContactContext from './ContactContext';
function ContactPage() {
const { contactName } = useContext(ContactContext);
return <div>Contact Name: {contactName}</div>;
}
but a little warning. If you use a lot of context based components, code becomes very quickly bad maintainable. I would give you the idea to replace the name with a kind of ID and define it as part of the route.