Redux

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

Basic example Jump to heading

// index.ts
import { connect } from 'react-redux'

import { Component, mapStateToProps, mapDispatchToProps } from './Component'

export const ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(UnconnectedComponent)
// Component.tsx
import React from 'react'
import { doClearQuery } from './some/file/of/action/creators'

const Component = ({ query, results, clearQuery }) => (
<div>
query:
{query}
<button onClick={clearQuery}>Clear</button>
<ul>
{results.map((result) => (
<li>
<img src={result.url} alt={result.title} />
{result.title}
</li>
))}
</ul>
</div>
)

// mapStateToProps
// For our select function we're returning an object using
// the implicit return and wrapping it in `()`
const mapStateToProps = (appState) => ({
results: appState.results,
query: appState.query,
})

// mapDispatchToProps
// We could also use object shorthand here to avoid
// building an object, as long as we're OK with the
// props being named the same thing
const mapDispatchToProps = { clearQuery: doClearQuery }

Selectors Jump to heading

export const getSignedInStatus = (user) => user.isSignedIn
export const getFullName = (user) => `${user.firstName} ${user.lastName}`
export const getUsername = (user) => user.username

← Back home