Is there a more efficient method for integrating useParams within my context provider?

Currently, I am exploring context and working with a route: /show/:id

In my context, I need to access the params ID of /show/:id. To achieve this, I initialized a state to an empty string in my context and utilized useParams in /show/:id to set the id.

Although it functions as intended, I can't help but wonder if there is a more efficient way to accomplish this and improve the cleanliness of my code.

This is how my app.js is structured:

<Route exact path="/discover" component={Discover} />
   <ShowDetailsProvider>
      // here I want :id in "showDetailsProvider"
     <Route exact path="/show/:id" component={ShowDetails} />
   </ShowDetailsProvider>
 <Route exact path="/show/episode/:id" component={ShowEpisode} />

Here is my ShowDetailsContext definition:

import { createContext, useState } from "react";

const ShowDetailsContext = createContext();

const ShowDetailsProvider = ({ children }) => {
  const [idSerie, setIdSerie] = useState("");

  console.log(idSerie);

  return <ShowDetailsContext.Provider value={{ setIdSerie }}>{children}</ShowDetailsContext.Provider>;
};

export { ShowDetailsProvider, ShowDetailsContext };

And this is my ShowDetails.js file:

import React, { useContext } from "react";
import { useParams } from "react-router-dom";
import { ShowDetailsContext } from "../context/ShowDetailsContext";

const ShowDetails = () => {
  const showDetailsContext = useContext(ShowDetailsContext);
  const { id } = useParams();
  showDetailsContext.setIdSerie(id);

  return (
    <>
      <p>Show detail page</p>
    </>
  );
};

export default ShowDetails;

Answer №1

From my perspective, the layout appears to be clean, straightforward, and easily digestible. However, I do have one observation regarding the practice of capturing the id in context. Unless there are additional reasons for doing so, it may create unnecessary redundancy within the structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

I encountered an error while using react-create-app: "./src/index.css (./node_modules/react-scripts/node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1"

Recently, I started a project with create-react-app and everything was smooth sailing until this morning. Even the font wasn't causing any issues. Upon running npm start, I encountered the following error message: ./src/index.css (./node_modules/react ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Having trouble with my Nextjs weather app attempting to fetch an API. Unsure of what I am doing incorrectly as I keep receiving an unauthorized error

Is my API handling implementation correct? Or could there be something crucial that I am overlooking? Originally, this project was created using a React app and now I am attempting to transition it to Next.js, so maybe there is something specific about how ...

ReactJS: Understanding the Interconnectedness of Components

In my application, I have two main components: Table (which is a child of Tables) and Connection (which is a child of Connections). Both Tables and Connections are children of the App component. The issue I am facing is that the Table component needs to be ...

Changing the global type in TypeScript

Currently, I am incorporating two third-party TypeScript libraries into my project. Interestingly, both of these libraries expose a global variable with the same name through the Window interface. However, they offer different methods for interacting with ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

Troubleshooting: Why isn't makeStyles adding dynamic style to Material UI Menu?

I'm attempting to dynamically generate classes for the material ui Menu using the following approach : const useStyles = (props) => { return makeStyles({ paper: props.style, }); }; const StyledMenu = (props) => { const classes = useSt ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

Implement Google Analytics tracking in Next.js application using the next-redux-wrapper library

I've successfully developed a nextjs app with redux wrapper. class MyApp extends React.Component<AppProps> { public static getInitialProps = wrapper.getInitialAppProps(store => async ({ Component, ctx }) => { Now I'm in the p ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

Tips for preventing the initial default effect in UseEffect

I've added a new feature where clicking a button triggers an alert saying 'you have clicked'. However, the alert pops up as soon as the page loads and I don't want that. I'd like the alert to only appear when the count reaches 1 or ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

The className property of a Material UI form input component

Following along with this specific tutorial to delve into the concept of dynamic forms. It specifies using a custom name and id properties for input elements. <input type="text" name={ageId} data-id={idx} id={ageId} value={cats[idx].age} c ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...