Redux & Redux Toolkit
/Intermediate
connect() HOC
Definition
A legacy Higher-Order Component from React-Redux that connects a React component to the Redux store. It was the standard way to use Redux before Hooks (`useSelector`) were invented.
Explain Like I'm New
The old, confusing way to use Redux. You wrote two functions called `mapStateToProps` (reads data) and `mapDispatchToProps` (writes data), and glued them to your component at the very bottom of the file.
Real World Example
You will still see this in millions of lines of enterprise code written before 2019. If you get a job maintaining an older React Class Component application, you MUST know how `connect` works.
Common Use Cases
- •Maintaining legacy codebases
- •Class components
Interactive Example
/* ❌ LEGACY REDUX PATTERN (For historical reference) */ import { connect } from 'react-redux'; function UserProfile({ username, logout }) { return ( <div> <h1>{username}</h1> <button onClick={logout}>Log out</button> </div> ); } // 1. Map State to Props (The old useSelector) const mapStateToProps = (state) => ({ username: state.auth.username }); // 2. Map Dispatch to Props (The old useDispatch) const mapDispatchToProps = (dispatch) => ({ logout: () => dispatch({ type: 'auth/logout' }) }); // 3. Connect them all together export default connect(mapStateToProps, mapDispatchToProps)(UserProfile);
Interview Questions
basic
- Should you use `connect()` in a brand new React application today?
intermediate
- What does `mapStateToProps` do?