Pure and Impure Functions

Wanted to share an interesting point about pure and impure functions today.

Pure Functions are functions that do not depend on or modify any external state.

Similarly Impure Functions in React modify external state or DOM directly and depend on external factors.

Impure functions are sometimes necessary (e.g., for side effects) but should be carefully isolated using hooks or external utilities to maintain React's declarative nature and rendering efficiency.

Some common side effects are fetching data from an API, updating the document title with code, managing subscriptions or event listeners, saving data to local storage, animating DOM elements and interacting with third-party libraries like analytics, payments and maps.

In all this cases it is recommended to encapsulate the code within hooks.

We all are used to adding API calls within useEffect but interesting thing to note here is that localStorage manipulations are also recommended to be added within useEffect as it is also a side effect which at least I wasn't aware of before.

Here's an example:

useEffect(() => {

// Side effect: Saving theme preference to localStorage

localStorage.setItem('theme', theme);

}, [theme]); // Runs whenever `theme` changes

We store theme in local storage based on changes in state variable.