Apply for Zend Framework Certification Training

ReactJs






Increment and decrement count using redux

Step 1  Add some code in app.js

import { useDispatch } from 'react-redux';
import Count from './components/count';

function App() {
  const dispatch = useDispatch();
  return (
   <>
    <input type='button' value="Increment"  onClick={(e)=>dispatch({type:'INCREMENT'})}/>
      {<Count/>}
    <input type='button' value="Decrement"  onClick={(e)=>dispatch({type:'DECREMENT'})}/>
   </>
  );
}

export default App;


Step 2  Create an store 


import { createStore } from "redux";
const reducer=(state = 0,action)=>{
    switch (action.type) {
        case 'INCREMENT': return state+1
        case 'DECREMENT': return state-1
        default: return state  
    }
}
export const store = createStore(reducer)

 

 

Step 3 Create count.jsx

import { useSelector } from "react-redux"
const Count = ()=>{
    const count = useSelector(state=>state)
    return(
        <h2>{count}</h2>
    )
}
export default Count


Step 4 Add some code in index.js 

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { store } from './redux/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store ={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

 

< Context api in reactJs React Hooks Tutorial – useState by examples >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top