Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Redux - Hooks API

I'm trying to configure my new react-redux application to use the new features of React-Redux. The official documentation says

React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component.

I have been trying to find some helping articles related to Hooks API with some real examples but all react-redux Apps are using connect function. Official documentation also shows very basic examples.

I want to change the connect functions in my App with useSelector (offered by Hooks API).

Here is an example code snippet from my application.

//MessagesListContainer
export default connect(
  // mapStateToProps
  (state:State) => ({
    activeUser: getActiveUser(state),   
    messages: getMessagesList(state),   
  })
)(MessagesList)

//Selectors
export const getActiveUser = (state: State) => state.activeUser;
export const getMessagesList = (state : State) => (
  Object.keys(state.messages).map((key : any)=> state.messages[key])
)

export interface IMessagesListProps {
  activeUser?: User;
  messages?: Message[];
}
/**
 *  Messages List
 */
export default class MessagesList extends PureComponent<IMessagesListProps> {
.
.
.
}
like image 702
DevLoverUmar Avatar asked Mar 31 '20 11:03

DevLoverUmar


People also ask

Can you use Redux with react hooks?

We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript. These hooks were first added in v7.1.0.

Is react hook an API?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.


1 Answers

Hooks are not compatible with Class components. To use Hooks, you convert the class components to function components. For instance, your code can be refactored to

/**
 *  Messages List
 */

const getActiveUser = (state: State) => state.activeUser;
const getMessagesList = (state : State) => (Object.keys(state.messages).map((key : any)=> state.messages[key]));

const MessagesList: React.FC = () => {
  const activeUser = useSelector(getActiveUser);
  const messagesList = useSelector(getMessagesList);

  ....
}

export default MessagesList;
like image 50
Mike Perry Yeboah Attara Avatar answered Sep 19 '22 12:09

Mike Perry Yeboah Attara