Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Functional Programming with React

3 min readJan 30, 2024

--

Functional programming has emerged as a powerful paradigm in software development, and its principles are particularly relevant in the context of React. Before we get into how functional programming is implemented in ReactJs let’s look into what ‘Functional Programming’ exactly means.

Press enter or click to view image in full size
image src: Dall-E

Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming paradigm, which emphasizes changes in state.

Key principles of functional programming include:

  1. Immutability: Avoid changing data in place and instead create new data structures with updated values.
  2. Pure Functions: Functions that, given the same inputs, always return the same output and do not cause any side effects.
  3. First-Class and Higher-Order Functions: Treating functions as values that can be passed as arguments, returned from other functions, and assigned to variables.
  4. Declarative Rather Than Imperative: Describing what the program should accomplish rather than detailing the steps to achieve it.

Functional Programming in React

React, at its core, embraces functional programming principles, especially with the introduction of hooks. The use of functional components, hooks, and immutable state management aligns well with FP concepts.

Immutable State Updates

In React, state should be treated as immutable. This means when you want to update the state, you should not modify it directly but instead return a new object that represents the new state.

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const incrementCount = () => {
setCount(prevCount => prevCount + 1);
};

return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}

Pure Components

A pure component is one that always renders the same output for the same state and props. React offers React.memo for creating pure functional components.

import React, { memo } from 'react';

const PureComp = memo(props => {
// This component will only re-render if props change
return <div>{props.message}</div>;
});

Higher-Order Components

A higher-order component (HOC) is a function that takes a component and returns a new component. It’s a pattern that’s derived from React’s compositional nature and is a good example of functional programming.

import React from 'react';

function withLogger(WrappedComponent) {
return function(props) {
console.log('Props:', props);
return <WrappedComponent {...props} />;
};
}

// Usage
// const EnhancedComponent = withLogger(OriginalComponent);

Hooks as First-Class Functions

Hooks in React, like useState and useEffect, are first-class functions that can be used inside functional components to handle state and side effects in a functional manner.

import React, { useState, useEffect } from 'react';

function ExampleComponent() {
const [data, setData] = useState(null);

useEffect(() => {
fetchData().then(setData);
}, []); // Empty array ensures this runs once, similar to componentDidMount

// render logic
}

Functional programming in React brings several benefits, including cleaner and more predictable code, easier testing, and a more declarative style of programming. Whenever you work with ReactJs ask yourself if your code is adhering to functional programming for the best experience.

Get Ali Husen’s stories in your inbox

Join Medium for free to get updates from this writer.

Follow me if you enjoyed my content & buy me a coffee if you are feeling super generous :)

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--