Level Up Your React Skills: 10 Advanced Code Snippets with Examples

Sourabh Mourya

Sourabh Mourya

Sr. Software Developer
Share on facebook
Share on twitter
Share on pinterest
Share on linkedin
React Development

React is one of the most popular front-end frameworks used by developers around the world to build complex and scalable web applications. While React provides a solid foundation for building modern web applications, mastering its advanced techniques and best practices can be challenging. That’s where advanced code snippets come in handy.

React Development
10 Advanced Code Snippets with Examples

In this article, we’ve compiled 10 advanced React code snippets that can help developers level up their skills and solve common problems with ease. Each code snippet is accompanied by a clear explanation and practical example, making it easy for developers to understand and implement them in their own projects. From managing state and props to optimizing performance and styling components, these code snippets cover a wide range of topics in advanced React development.

here are 10 advanced code snippets with examples for React

Whether you’re a seasoned React developer or just starting out, these code snippets are sure to help you take your skills to the next level. So, let’s dive in and explore how these advanced techniques can make your React applications more powerful and efficient.

1. Higher-Order Components:

const withAuthentication = (Component) => {
  const AuthenticatedComponent = () => {
    const isAuthenticated = checkAuthentication();
    return isAuthenticated ? <Component /> : <Redirect to="/login" />;
  };
  return AuthenticatedComponent;
};

This is a higher-order function in React that returns a new component. The purpose of this function is to check if the user is authenticated before rendering a component. The function takes a component as an argument and returns a new component that wraps around it.

The new component created by this function is called “AuthenticatedComponent“. It checks if the user is authenticated by calling the function “checkAuthentication()“, which is not defined in the code snippet. If the user is authenticated, it returns the component passed as an argument. Otherwise, it redirects the user to the login page by using the React Router’s Redirect component and passing “/login” as the path.

This code is useful for implementing authentication in a React application. By wrapping components with this higher-order function, developers can ensure that only authenticated users can access certain parts of the application. This helps improve the security of the application and provides a better user experience.

2. Render Props:

const MouseTracker = ({ render }) => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const handleMouseMove = (event) => setPosition({ x: event.clientX, y: event.clientY });
  return <div onMouseMove={handleMouseMove}>{render(position)}</div>;
};

This is a functional component in React that takes a “render” prop and returns a div element with an “onMouseMove” event listener. The purpose of this component is to track the position of the mouse cursor on the screen and pass the position data to the “render” prop function.

The component uses the “useState” hook to define a “position” state variable, which is an object with two properties: “x” and “y“, both initialized to 0. The “handleMouseMove” function is defined to update the “position” state with the current x and y coordinates of the mouse cursor every time the “onMouseMove” event is triggered.

The component then returns a div element with the “onMouseMove” event listener set to call the “handleMouseMove” function. The “render” prop function is called and passed the “position” object as an argument to render the content based on the current position of the mouse cursor.

This code can be useful for creating interactive components in React that respond to the user’s mouse movements. By passing a custom render function to this component, developers can implement various behaviors, such as animations, tooltips, or other visual effects, that depend on the mouse position.

3. Custom Hooks:

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight });
  useEffect(() => {
    const handleResize = () => setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return windowSize;
};

This is a custom React hook that allows developers to retrieve the current size of the browser window. The hook uses the “useState” hook to define a state variable called “windowSize“, which is an object containing the initial width and height of the window.

The hook also uses the “useEffect” hook to add an event listener to the window object that listens for the “resize” event and updates the “windowSize” state variable with the new width and height values of the window.

The hook is then returned, which provides the current window size as the return value. Developers can use this hook to create responsive components that change their layout or behavior based on the size of the browser window.

In summary, this custom hook is a useful utility function that simplifies the process of retrieving the current size of the browser window in a React application.

4. Memoization:

const MemoizedComponent = React.memo(Component);

This is a higher-order component in React that uses the “React.memo” method to create a memoized version of a functional component called “Component“.

Memoization is a technique used to optimize the performance of components in React by caching the results of expensive computations and reusing them when possible. Memoization can help reduce the number of renders a component needs to perform and improve the overall performance of the application.

The “React.memo” method is a built-in optimization in React that allows developers to memoize a functional component. When a memoized component receives the same props, React will reuse the previously rendered result instead of re-rendering the component.

The code snippet above creates a memoized version of the “Component” functional component and assigns it to a new variable called “MemoizedComponent“. This memoized version of the component can help improve the performance of the application by avoiding unnecessary re-renders.

This code can be useful for optimizing the performance of components in a React application that rely on expensive computations or render large amounts of data. By using memoization, developers can improve the user experience and make their applications more efficient.

5. Lazy Loading:

const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Suspense fallback={<LoadingSpinner />}>
  <LazyComponent />
</Suspense>

This code uses React’s “lazy loading” feature to asynchronously load a component called “LazyComponent” only when it’s needed, instead of loading it upfront.

The “React.lazy” function is used to create a new component that is loaded lazily when it is actually needed. This function takes a function that returns a dynamic import statement which specifies the module that contains the lazily loaded component.

The “Suspense” component is used to display a fallback UI, such as a loading spinner, while the lazily loaded component is being loaded. This component allows developers to handle asynchronous operations in a declarative way.

In this code, the “LazyComponent” is loaded lazily using the “React.lazy” function and then rendered inside the “Suspense” component, which displays a loading spinner until the component is fully loaded.

Overall, this technique can help improve the performance of a React application by reducing the initial load time and only loading components when they are actually needed.

6. Server-Side Rendering:

const app = express();
app.use(express.static('public'));
app.get('*', (req, res) => {
  const markup = renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>My App</title>
      </head>
      <body>
        <div id="root">${markup}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `);
});


This code sets up a basic server using the Express framework for Node.js. It serves static files from the “public” directory using the “express.static” middleware.

The server also has a catch-all route that responds to any incoming request using a callback function. The callback function generates a server-side rendered HTML markup for a React component called “App” using the “renderToString” function from the “react-dom/server” module.

The rendered markup is then sent as a response to the client, along with an HTML document that includes a script tag pointing to a client-side JavaScript bundle called “bundle.js“. The client-side script is responsible for mounting the React component on the page.

Overall, this technique of server-side rendering can help improve the performance and SEO of a React application by pre-rendering the initial HTML markup on the server and sending it to the client. This allows for faster page load times and better search engine indexing.

7. Context API with Reducer:

const initialState = { count: 0 };
const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};
const CounterContext = React.createContext(initialState);
<CounterContext.Provider value={useReducer(reducer, initialState)}>
  <App />
</CounterContext.Provider>

This code sets up a React context called “CounterContext” with an initial state object containing a single property called “count” with a value of 0.

It also defines a reducer function that takes a state and an action and returns a new state based on the action type. In this case, the reducer can handle two action types: “INCREMENT” and “DECREMENT“, which respectively increase or decrease the count value by 1.

The context is then used to wrap the root component of the application, which in this case is “App“. The value prop of the context provider is set to the result of calling the “useReducer” hook with the reducer function and the initial state object.

This allows any child component within the application to access the current state and dispatch actions to update it using the “useContext” hook. By using a context and a reducer, the application can manage more complex state logic and avoid prop drilling.

8. React Router with Code Splitting:

const HomePage = lazy(() => import('./HomePage'));
const AboutPage = lazy(() => import('./AboutPage'));
<BrowserRouter>
  <Suspense fallback={<LoadingSpinner />}>
    <Switch>
      <Route exact path="/" component={HomePage} />
      <Route path="/about" component={AboutPage} />
    </Switch>
  </Suspense>
</BrowserRouter>

This code sets up a client-side routing for a React application using the “react-router-dom” package.

It defines two lazy-loaded components, “HomePage” and “AboutPage“, which are only loaded when needed to reduce the initial bundle size.

It then wraps the router component, “BrowserRouter“, around a “Switch” component that defines the routes for the application. The “Switch” component renders the first matching route among its children, and the “exact” prop is used to ensure that only the exact “/” path is matched for the “HomePage” component.

The “Suspense” component is used as a fallback to display a loading spinner while the lazy-loaded components are being loaded. It wraps the “Switch” component and sets the “fallback” prop to the loading spinner component.

Overall, this code sets up a basic client-side routing for the React application, with lazy-loading and a loading spinner as a fallback.

9. Controlled Components:

const [formData, setFormData] = useState({ username: '', password: '' });
const handleInputChange = (event) => {
  setFormData({ ...formData, [event.target.name]: event.target.value });
};
<input type="text" name="username" value={formData.username} onChange={handleInputChange} />

10. CSS-in-JS with Styled Components:

import styled from 'styled-components';
const Button = styled.button`
  background-color: ${props => props.primary ? 'blue' : 'white'};
  color: ${props => props.primary ? 'white' : 'blue'};
`;
<Button primary>Click me!</Button>

This code defines a styled button component using the styled-components library. The component accepts a primary prop that determines whether the button should have a blue background and white text or a white background and blue text.

The background-color and color properties are set using a ternary operator that checks the value of the primary prop. If primary is truthy, the button will have a blue background and white text. If primary is falsy, the button will have a white background and blue text.

The styled button component can be used by placing the <Button> element in the JSX code and passing the primary prop to customize the button’s appearance.

These advanced code snippets demonstrate the full potential of React, showcasing how to implement complex functionalities and solve common problems with ease. Each snippet is accompanied by a brief explanation and practical example, making it easy for developers to apply them in their projects and enhance their skills.

From managing state and props to optimizing performance and styling components, these code snippets cover a wide range of topics in advanced React development. Whether you’re a seasoned React developer or just starting out, these snippets are sure to help you take your skills to the next level.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Stories