Home > Net >  [React]what is the "best React practice" to handle events in-between different components
[React]what is the "best React practice" to handle events in-between different components

Time:04-13

So... I have a simple app that makes a note. Like MacOS Memo app. I have "add card" button and list of "memo"s. I can swipe memos to reveal card options like delete, archive etc..

screenshot of the app

Whenever I click "add card", I want all of the states of memos to reset.(such as swipe opened state back to false).

But problem is that "add card" and each memo card is all different component and have no access to each other. How am I supposed to let the memo component know that "add card" button has been clicked?

I am new to React, and I almost feel like React is not built for such action.

CodePudding user response:

You have two main options here, useContext and redux. If you don't have any complex logic and don't need a global state that should be shared across your whole app, go with useContext, otherwise you should use redux who is more complex to implement.

The main goal of useContext is to avoid prop drilling, the kind of situation where you pass props between many components. So you wrap all the components that should access the state with a context provider and can get this state from any component who is wrapped by the provider, please read the docs to learn more about the useContext.

Another option is redux, who is much more complex and probably you will need at least one week to understand and apply the concepts, so i suggest to just use redux when you have an app with complex state logic that really need a better global state management. Anyway, knowledge is always welcome, so read the redux docs and also watch this video about redux.

  • Related