React hooks with redux


Posted 1 month ago by Ryan Dhungel

Category: React Hooks

Viewed 190 times

Estimated read time: 2 minutes

This is an example code to use hooks with redux. This is a siple counter app with input field where user can enter their name. This is to demonstrate to you how you can combine multiple reducers and create one single rootReducer to create global state in react.

 

Example app using react hooks with redux

 

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
// 1. import redux
import { createStore, combineReducers } from "redux";
import { Provider, useSelector, useDispatch } from "react-redux";

// 2. create reducer/s
// reducers are functions that will update state
function nameReducer(state = {}, action) {
  switch (action.type) {
    case "UPDATE_NAME":
      return action.payload;
    default:
      return state;
  }
}
// 3. combine reducer
// you can add more than one reducer here
const rootReducer = combineReducers({
  name: nameReducer,
});

// 4. create store
// requiers reducers and initial state
const store = createStore(rootReducer, {});

// 5. provide store
// once store is ready provide it to components
function App() {
  return (
    <Provider store={store}>
      <Name />
    </Provider>
  );
}

// 5. access/update state
function Name() {
  // allows you to extract data from the Redux store state
  const { name } = useSelector((state) => ({ ...state }));
  // const { name } = useSelector((state) => ({
  //   name: state.name,
  // }));

  // use dispatch method to update state
  const dispatch = useDispatch();

  function handleUpdateName(event) {
    dispatch({
      type: "UPDATE_NAME",
      payload: event.target.value,
    });
  }

  return (
    <div>
      <p>{JSON.stringify(name)}</p>
      <input placeholder="Input your name" onChange={handleUpdateName} />
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);