Transitioning from React Class Components to React Hooks; Using Redux with React Hooks

source
export class Example extends React.Component {   constructor(props) {     super(props);     this.state = {         age: 5         };       }  componentDidMount() {    this.setState({age: this.props.age})  } render() {  return (    <div>     <h1> Age : {this.state.age} </h1>    </div>  );}}
export function Example(props) {const [age, setAge] = useState(5);useEffect(() => {setAge(props.age);}, [props.age]);return (<div><h1> Age : {age} </h1></div>);}
import { connect } from 'react-redux'
import { increaseage } from "../redux/actions"
class Example extends React.Component {render() {const { age } = this.props;return (<div><h1 onClick={()=>this.props.increaseage}> Age : {age} </h1></div>);}}const mapStateToProps = (state) => { const { age } = state.statename return {age} }const mapDispatchToProps = { increaseage }export default connect(mapStateToProps, mapDispatchToProps)(Example)
import React from "react";import { useDispatch, useSelector } from "react-redux";import { increaseage } from "../redux/actions"const Example = () => {const age = useSelector(state => state.statename.age);const dispatch = useDispatch();return (       <div>          <h1 
onClick={() => dispatch(increaseage(age++))}>
Age : {age}
</h1>
</div> )}export default Example;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store