DEV Community

Cover image for How to use reduce with React?
sathish bottula
sathish bottula

Posted on

How to use reduce with React?

What is the use of reduce in Javascript?

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

let a=[1,5,6,7,8];
let total=a.reduce((total,currentValue)=>total+currentValue)
console.log(total);//prints 27
Enter fullscreen mode Exit fullscreen mode

In the above example, we are using reduce for sum of array.

What in case if you want to pass a value to accumulator?

reduce accepts two params function, param.

let a=[1,5,6,7,8];
let total=a.reduce(((total,currentValue)=>total+currentValue),20)
console.log(total);//prints 47
Enter fullscreen mode Exit fullscreen mode

How to use reduce in react now?

import React, { Component } from 'react'

export default class App extends Component {
  render() {
    let a=[1,5,6,7,8];
    let total=a.reduce(((total,currentValue)=>total+currentValue),20)

    return (
      <div>
        Total sum is {total}    
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)