Boosting app performance with React-Tracked

    Dec 4, 20248 min read272 viewsUpdated:Dec 9, 2024
    Boosting app performance with React-Tracked

    React Tracked is a library designed to improve performance by preventing unnecessary re-renders in global state management. Unlike React's useContext, which can trigger re-renders when any part of the state changes, React Tracked uses Proxies to track which parts of the state are accessed and only re-renders components if those specific properties change. This helps with deep nested objects as well.

    Initially, React Tracked was used to replace React Context for global state management. But since version 1.6.0, it can work alongside libraries like React-Redux by adding "state usage tracking" to any selector-based hooks, improving performance without requiring deep knowledge of object reference equality.

    Understanding State Management in React

    Common Challenges

    • State Immutability: Keeping the state immutable (unchanged) can lead to long, complex code.

    • Complex Updates: As your state grows and becomes more detailed, updating it can be difficult and prone to mistakes.

    • Re-renders: Unnecessary re-renders can slow down performance if state changes are not managed well.

    Introducing react-tracked

    react-tracked is a small, lightweight library that uses React's Context API to share state between components without causing unnecessary re-renders. On the other hand, use-reducer-async is a tool for handling asynchronous actions in state management, making it easier to handle actions like fetching data from APIs.

    By combining react-tracked and use-reducer-async, you can efficiently manage both synchronous and asynchronous state changes, resulting in faster and more responsive applications.

    Using react-tracked optimizes re-renders by tracking property access and only triggering re-renders in child components that rely on the updated state.

    After installing react-tracked, re-renders are only triggered when the child component accesses the changed state property, minimizing unnecessary updates.

    The parent component manages the global state, but react-tracked ensures that only relevant child components re-render when a state changes.

    Can React Tracked Replace Redux?

    React Tracked can be a simpler and more efficient option to replace Redux for state management in React apps. It uses React's context and hooks, but it improves performance by only re-rendering the components that actually use the parts of the state that have changed. In Redux, state updates can cause more components to re-render even if they don’t need to.

    With React Tracked, you don't have to create actions, reducers, or handle a global store like in Redux. Instead, the state is stored using React’s context, and Proxies track which components access specific state properties. This helps reduce unnecessary re-renders.

    It makes state management easier to set up, especially for apps that don’t need Redux's more complicated features like middleware. React Tracked keeps things simple, with fewer steps and better performance, without the extra code and complexity of Redux.

    React Tracked working: An Example

    Installation:

    Install this library using npm or yarn in your project.

    npm install react-tracked # Or yarn add react-tracked

    1. App.js.js (Context with react-tracked)

    This file serves as the main entry point for the application. It wraps the EditPerson and ShowPerson components within the Provider from the store. This context provider ensures that both components have access to the shared state managed by react-tracked.

    import React from 'react';
    
    import { Provider } from './store';
    import EditPerson from './EditPerson';
    import ShowPerson from './ShowPerson';
    
    const App = () => (
      <Provider>
        <EditPerson />
        <ShowPerson />
      </Provider>
    );
    
    export default App;
    

    2. Store.js

    In this file, a context store is created using react-tracked. It initializes a state object with useState and exports a Provider, a hook to access the tracked state (useTrackedState), and a hook to update the state (useSetState). The useUpdate function is renamed to useSetState for clarity.

    import { useState } from 'react';
    import { createContainer } from 'react-tracked';
    
    const useValue = () => useState({});
    
    export const {
      Provider,
      useTrackedState,
      useUpdate: useSetState,
    } = createContainer(useValue);
    

    3. EditPerson.js

    This component allows users to input and edit a person's first and last name. It uses useSetState to update the state and useTrackedState to access the current state. The input fields are controlled components, meaning their values are derived from the state.

    import React from 'react';
    
    import { useSetState, useTrackedState } from './store';
    
    const EditPerson = () => {
      const setState = useSetState();
      const state = useTrackedState();
      const setFirstName = (e) => {
        const firstName = e.target.value;
        setState((prev) => ({ ...prev, firstName }));
      };
      const setLastName = (e) => {
        const lastName = e.target.value;
        setState((prev) => ({ ...prev, lastName }));
      };
      return (
        <div>
          <div>
            First Name:
            <input value={state.firstName || ''} onChange={setFirstName} />
          </div>
          <div>
            Last Name:
            <input value={state.lastName || ''} onChange={setLastName} />
          </div>
        </div>
      );
    };
    
    export default EditPerson;

    4. ShowPerson.js

    This component displays the first name or full name based on user preference. It uses local state (onlyFirstName) to toggle between showing just the first name and the full name. It also leverages the useTrackedState to access the global state management.

    import React, { useState } from 'react';
    
    import { useTrackedState } from './store';
    import { useFlasher } from './utils';
    
    const ShowPerson = () => {
      const state = useTrackedState();
      const [onlyFirstName, setOnlyFirstName] = useState(false);
      return (
        <div ref={useFlasher()}>
          <button type="button" onClick={() => setOnlyFirstName((s) => !s)}>
            {onlyFirstName ? 'Showing only first name' : 'Showing full name'}
          </button>
          {onlyFirstName ? (
            <div>First Name: {state.firstName}</div>
          ) : (
            <div>
              Full Name: {state.firstName} {state.lastName}
            </div>
          )}
        </div>
      );
    };
    
    export default ShowPerson;

    5 utils.js

    This file contains the useFlasher utility function, which adds a visual effect (a flashing box shadow) to the component when it renders. It uses the useRef and useEffect hooks to manipulate the DOM.

    import { useRef, useEffect } from 'react';
    export const useFlasher = () => {
      const ref = useRef(null);
      useEffect(() => {
        if (!ref.current) return;
        ref.current.setAttribute(
          'style',
          'box-shadow: 0 0 2px 1px red; transition: box-shadow 100ms ease-out;',
        );
        setTimeout(() => {
          if (!ref.current) return;
          ref.current.setAttribute('style', '');
        }, 300);
      });
      return ref;
    };


    Read more here: Using useRef Hooks in React Applications

    What is the difference between regular react and react-tracked

    Using regular React with context or props for managing state is different from using react-tracked. In regular React, when the state changes, it causes the whole component to re-render. With react-tracked, only the components that use the changed state will re-render, which can be more efficient.

    Because of how react-tracked manages updates, it can help improve the performance of your app, especially when dealing with larger applications or more complex states.

    State Management Approach

    In regular React, state management usually uses built-in hooks like useState and useContext. While these hooks make it easy to manage state, any updates can cause all components that use the context to re-render, even if they don’t actually need to. This can lead to performance problems as the application gets bigger.

    On the other hand, React Tracked uses a container-based approach with createContainer. This method allows components to access only the specific state properties they need. As a result, only the components that access changed properties will re-render, reducing unnecessary updates.

    React Tracked uses Proxies to track which properties a component accesses, so re-renders happen only when those specific properties change.

    Performance Considerations

    In larger applications, regular React can struggle with performance because it often re-renders many components when only one needs to update. React Tracked solves this problem by preventing unnecessary re-renders.

    This leads to better performance, especially in applications with complex UIs or large lists of data. It also makes state management easier for developers, letting them focus on the state their components actually need.

    Create Faster & More Performance-Driven React Apps!
    Angular minds as a top
    ReactJS web development company, we specialize in boosting performance using powerful tools like React-Tracked. Start your next ReactJS project with us today!

    Performance Increments with React Tracked

    performance increments with react tracked

    Reduced Re-renders

    React Tracked significantly lowers the number of re-renders because it only updates components that access changed state properties. In some cases, this can result in 30% to 70% less render time compared to using regular context-based state management, depending on the application’s size and complexity.

    Improved Responsiveness

    By optimizing how components render, applications using React Tracked respond more quickly to user interactions, creating a smoother experience, especially in apps that manage a lot of states.

    Scalability

    As applications grow, using React Tracked for state management becomes more efficient. It helps maintain performance without needing major changes to the codebase. This is particularly helpful in large applications where too many re-renders can slow things down.

    Batching State Updates

    Using the reducer pattern in react-tracked, multiple state updates can be combined into a single re-render. This boosts performance, especially when several actions need to update the state at the same time.

    Avoiding Prop Drilling

    React-tracked makes state management easier by removing the need to pass props through many layers of components. This results in cleaner code and reduces unnecessary re-renders of components.

    Integration with Asynchronous Actions

    When using asynchronous functions (like fetching data from an API), react-tracked helps manage state updates in an organized way. This improves performance by controlling when components should re-render based on the data-fetching process.

    Optimized State Management

    Since react-tracked works smoothly with React hooks, it enables more efficient and simple ways to manage state, leading to cleaner, more maintainable code and better performance.

    Conclusion

    Overall, while normal React provides sufficient tools for state management in small applications, as the complexity increases, react-tracked offers a more refined and performance-oriented approach.

    It enhances performance by minimizing unnecessary re-renders, which is crucial for applications with a large, shared state and many components that depend on it.

    By adopting react-tracked, developers can build more responsive, scalable applications that maintain high performance even as they grow in size and complexity.

    24
    Share
    Hire React Developers
    Hire React Developers
    Our React developers are timezone compatible and you can hire a team of our experts in just two days. Book a call with our CEO today.
    Hire Now

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.