"Unveiling the secret: How to effortlessly tap into the props and functions of

As a newcomer to React/NextJS with Redux in TypeScript, I have found the Redux setup process to be quite cumbersome. After following common tutorials to create the store, reducers, and actions, I realized that there might be a better way to handle it. In my _app.tsx file, I wired up the Provider component like this:

import { Provider } from 'react-redux'
import store from '@store/store'

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  )
}

export default MyApp

Then, for connecting state to props and integrating Redux in my index.tsx, I followed this approach:

import { StoreState } from '@store/reducers'

import {
  IData1,
  IData2,
  function1,
  function2,
  function3,
  function4,
  function5,
} from '@store/actions'

interface IProps {
  data1: IData1[]
  data2: IData2
  function1: Function
  function2: Function
  function3: Function
  function4: Function
  function5: Function
}

const _Home: NextPage<IProps> = (props) => {
  const {
    data1,
    data2,
    function1,
    function2,
    function3,
    function4,
    function5,
  } = props

  return (<div>
    <SomeComponent fct5={fonction5}
  </div>)
}

const mapStateToProps = (
  state: StoreState
): { data1: IData1[]; data2: IData2 } => {
  return { data1: state.data1, data2: state.data2 }
}

const Home = connect(mapStateToProps, {
  function1,
  function2,
  function3,
  function4,
  function5,
})(_Home)

export default Home

Although I managed to make it work, I must admit that the process felt overly complex and redundant. Am I missing a more efficient method of achieving the same results? Your insights would be greatly appreciated.

Furthermore, when it comes to utilizing Redux actions or accessing stored data in other components, what approach should I take? Should I repeat the connect wiring for every component or opt for a different strategy such as passing functions and data through component attributes like in the case of function5?

Answer №1

Steering you towards a different path: If react-redux isn't your cup of tea, consider utilizing React context and React dispatch instead. Reducers become simple functions that accept a state and an action as input and produce a new state as output.

Exploring React context:

import React, { useContext } from 'react'

// create context using react
const context = React.createContext<T | null>(null);

// Utilize React hook for context
useContext(context);

// Define React typing for Actions to be dispatched
React.Dispatch<Action>

Answer №2

If you're looking for a more efficient way to manage state in your application, I highly recommend using Zustand over Redux or the Context API.

Zustand is user-friendly and significantly reduces the amount of boilerplate code required. Additionally, you can integrate Zustand seamlessly without having to wrap it around every component, providing greater flexibility in managing state with minimal effort.

Take a look at this example:

within my ./store directory

import create from "zustand";
import { MyCustomType } from "./types";

export const cartStateStore = create<MyCustomType>((set) => ({
  open: false,
  setOpen: (val) => set(() => ({ open: val })),
}));

Then, easily import the value into any component and utilize the hook:

import { MyCustomType  } from "../lib/store"

const MyComponent = () => {
  const open = MyCustomType ((state) => state.open);
  const setOpen = MyCustomType ((state) => state.setOpen);

//setOpen(true)
//console.log(open)
}

It's as straightforward as that. Say goodbye to the excess overhead associated with Redux or context API usage. [1]: https://github.com/pmndrs/zustand

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

(modify) Activation of work functionality in Angular 2 strictly tied to pressing enter

I am working on a feature that displays rows matching a user-entered value in a dynamic list. The list should update as the user types in values, so I attempted to use a (change) event listener on the input text box. However, the list only updates when I ...

Leveraging Docker for a Next.js frontend application, utilizing the getServerSideProps function to fetch

In our docker orchestration setup, we have an API and web frontend in nextJS along with various other services. All requests are managed by a proxy service. After some trial and error, I was able to discover the correct address using a bridged network in ...

How to display an IconButton within a MenuItem only when it's not selected

How can I display an icon button inside an option (<MenuItem/>) like this? Additionally, how can I make the icon button invisible if it is selected? This is my current script: <TextField label="Payment Method History" select full ...

A step-by-step guide to importing the RxJs module directly into the browser after compiling Typescript, without the use of Angular, Webpack, or

My RxJs code is currently running on Node, compiling to Script.js after TS compilation with the following lines: Object.defineProperty(exports, "__esModule", { value: true }); var rxjs_1 = require("rxjs"); var operators_1 = require(&quo ...

Tips for writing unit tests for an object with a type union in TypeScript, Karma, and Sinon

Currently, I am conducting unit-testing for a project that utilizes TypeScript with the Angular framework. I am using Karma with Mocha and Chai frameworks for this purpose. The project includes an interface for the object, defined as follows: interface IS ...

Leveraging the `--max-http-header-size` flag with ts-node

Encountered an issue when trying to use ts-node with the --max-http-header-size 15000 flag. It works fine with regular node, but unfortunately, ts-node does not support that option ...

Determining the parent type in Typescript by inferring it from a nested member

Typescript has the ability to infer the type of a value based on queries made within if statements. For instance, the type of one member of an object can be deduced based on another: type ChildType = 'a' | 'b'; type Child<T extends ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

The field 'password' is not found in the data type 'User | undefined'

Howdy everyone, I've encountered an issue stating "Property '_doc' does not exist on type 'User & { _id: ObjectId; }'" in one of my controller documents while trying to fetch a particular user. My backend database is implemented us ...

Navigating with Angular: Transmitting dynamic URL parameters to components

I currently have the following routes defined: const routes: Routes = [ { path: ':product/new', children: [{ path: 'std/:country', component: SignUpComponent, data: { ...

What is the process for subscribing to setInterval() in an Angular application?

I'm currently working on developing an iOS location tracking application using the Ionic 5 Framework, Angular, and the Cordova Geolocation Plugin. In the past, I was able to track user location changes using the watchPosition() function, which worked ...

Is there a way to automatically extend my content to fill the space on the page below the Material UI AppBar?

I am currently using React and Material UI React to develop my application. My goal is to implement the AppBar component with content underneath, without causing the entire page to scroll. I want the content to occupy the maximum remaining height and the f ...

Using TypeScript with React Context

Currently, I am diving into the world of React! Our team has made a commitment to using Typescript. I find myself in a situation where I need to create a shopping cart for a bustling shopping center. The shopping cart will be utilized in t ...

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

A different approach to handling multiple constructors in Angular 4

Angular 4 does not support having multiple constructors, so I need to find a cleaner way to instantiate my object. This is what my model looks like: export class SrcFilter { constructor(public firstList?: Array<String>, public secondList?: Arra ...

"Enhance your shopping experience with React and Redux by implementing a powerful add to cart

Currently, I am tackling an issue with a shopping cart in ReactJs and Redux. The problem lies in adding an item to the cart - once added, it shows as undefined in the cart and does not display properly. Here is the snippet of code for the add to cart act ...

In TypeScript, vertical bars and null are commonly used for type unions

Greetings! I am just starting to learn JavaScript and TypeScript I have a question about the code snippet below What does the pipe symbol (|) signify? Also, why is null = null being used here? let element: HTMLElement | null = null; ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...