how to create a functional component that does not re render on state updates in javascript

One way to make a functional component not re-render on state updates is to use memoization. This can be achieved by using the React.memo higher-order component. The React.memo function takes a functional component as its argument and returns a new component that only renders when its props have changed.

Here's an example:

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

const MyComponent = memo(props => {
  // component logic
});

const App = () => {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <MyComponent onClick={() => setCount(count + 1)} />
    </div>
  );
};
272 chars
16 lines

In this example, the MyComponent function component is wrapped in the React.memo function. This ensures that the component is only re-rendered if its props have changed. The App component has state that changes when the button inside MyComponent is clicked. Since the prop being passed to MyComponent does not change, the component will not be re-rendered on state updates.

This technique can also be achieved with the useMemo and useCallback hooks, which allow you to memoize values and functions, respectively.

gistlibby LogSnag