Class component with Redux

As of version 7.x react-redux now has hooks for functional components

const store = useSelector(store => store)

So that we can use functional component with redux store like class component.

please check below link to get more idea about hooks

https://react-redux.js.org/next/api/hooks


Is it recommended to use functional components for components that have connection and interaction with the Redux store since those components that interact with the store do not have state locally.

Yes, it is recommended to use functional components with redux, and there is a way to have a local state in a functional component.


Why functional components are recommended?

The react ecosystem moves toward the use of hooks which means standardize the functional components.

As stated in docs about uses of hooks or classes:

In the longer term, we expect Hooks to be the primary way people write React components.


How to have a local state in functional components with redux?

Redux introduced redux-hooks API which gives functional components the ability to use local component state and allows to subscribe to the Redux store without wrapping your components with connect().

  • useSelector
  • useDispatch
  • useStore
// Creating a store
const store = createStore(rootReducer)

ReactDOM.render(
  <Provider store={store}>
    <CounterComponent />
  </Provider>,
  document.getElementById('root')
)

// CounterComponent.jsx Selector example
import React from 'react'
import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  // Using the store localy with a selector.
  const counter = useSelector(state => state.counter)
  return <div>{counter}</div>
}

// CounterComponent.jsx Dispatch Example
import React from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  // Dispatching an action
  const dispatch = useDispatch()

  return (
    <div>
      <span>{value}</span>
      <button onClick={() => dispatch({ type: 'increment-counter' })}>
        Increment counter
      </button>
    </div>
  )
}

// CounterComponent.jsx Referencing the store example
import React from 'react'
import { useStore } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const store = useStore()

  // EXAMPLE ONLY! Do not do this in a real app.
  // The component will not automatically update if the store state changes
  return <div>{store.getState()}</div>
}

Tags:

Reactjs

Redux