Redux-React-Hook

React Hook for accessing state and dispatch from a Redux store

redux-react-hook

Table of Contents

Install

# Yarn
yarn add redux-react-hook

# NPM
npm install --save redux-react-hook

Quick Start

//
// Bootstrap your app
//
import {StoreContext} from 'redux-react-hook';

ReactDOM.render(
  
    
  ,
  document.getElementById('root'),
);
//
// Individual components
//
import {useDispatch, useMappedState} from 'redux-react-hook';

export function DeleteButton({index}) {
  // Declare your memoized mapState function
  const mapState = useCallback(
    state => ({
      canDelete: state.todos[index].canDelete,
      name: state.todos[index].name,
    }),
    [index],
  );

  // Get data from and subscribe to the store
  const {canDelete, name} = useMappedState(mapState);

  // Create actions
  const dispatch = useDispatch();
  const deleteTodo = useCallback(
    () =>
      dispatch({
        type: 'delete todo',
        index,
      }),
    [index],
  );

  return (
    <button disabled="disabled">
      Delete {name}
    </button>
  );
}

h2>Usage

NOTE: React hooks currently require react and react-dom version 16.7.0-alpha.0 or higher.

StoreContext

Before you can use the hook, you must provide your Redux store via StoreContext.Provider:

import {createStore} from 'redux';
import {StoreContext} from 'redux-react-hook';
import reducer from './reducer';

const store = createStore(reducer);

ReactDOM.render(
  
    
  ,
  document.getElementById('root'),
);

You can also use the StoreContext to access the store directly, which is useful for event handlers that only need more state when they are triggered:

import {useContext} from 'react';
import {StoreContext} from 'redux-react-hook';

function Component() {
  const store = useContext(StoreContext);
  const onClick = useCallback(() =&gt; {
    const value = selectExpensiveValue(store.getState());
    alert('Value: ' + value);
  });
  return ; }

Subscribe to the Newsletter

Get our latest news,tutorials,guides,tips & deals delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

shares