Aquasar
  • Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact
WEB DEVELOPMENT |SEO |DIGITAL ADS

React Hooks useRedux Hook Set up

Jun 28th, 2019

Alex Quasar

reactuse-reduxreact hooks

See Link to github for cloning project: https://github.com/arhoy/react-hooks-useReducer-basic and git clone and run npm i in integrated terminal

The index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


export const UserContext = React.createContext();

const name = 'Kamala';

ReactDOM.render(
    <UserContext.Provider
        value = { name }
    >
        <App />
    </UserContext.Provider>
    ,document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

The App.js file

import React, { useContext, useReducer } from 'react';

import { UserContext } from './index';
import './App.scss';

const initialState = {
  count: 0
}

function reducer(state, action) {
  switch(action.type) {
    case 'increment':
      return {
        count: state.count + 1
      }
    case 'decrement':
      return {
        count: state.count -1
      }
    case "reset":
      return {
        count: initialState.count
      }
    default:
      return state;
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState)
  const value = useContext(UserContext);

  return (
    <div className="App">
      <p>Hey {value}</p>
      <button onClick = { () => dispatch( { type: 'increment' }) } >Add more</button>
      <button onClick = { () => dispatch( { type: 'decrement' }) } >Add less</button>
      <button onClick = { () => dispatch( { type: 'reset' }) } > Reset</button>
      <p> Count: { state.count } </p>
    </div>
  );
}

export default App;