Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to update local state if pros are changed in ReactJS

Getting Started

Before diving into the main topic of updating local state if props are changed in ReactJS, let's make sure we have a shared understanding of what 'state' and 'props' are.

In simple terms, the 'state' in ReactJS refers to a built-in object that stores property values belonging to a component. It's like a data holder. You can think of it like a memory box that your component can access at any time to recall certain information.

'Props', short for properties, are similar to arguments passed into a function in JavaScript. They allow components to communicate with each other. It's like a baton in a relay race being passed from one runner to the next.

Each of these elements plays a crucial role in managing data in ReactJS applications. Now, let's move on to our main topic.

Detecting Changes in Props

ReactJS components re-render whenever their state or props change. However, there's a catch. React doesn't automatically update the local state when props change. This is because the local state is initialized only once when the component mounts, and after that, it's completely independent.

You can think of it like setting an alarm. Once you set the alarm time (mounting the component and initializing the state), it will ring at that time no matter what. If you want to change the alarm time (update the state), you have to do it manually.

So, how do we manually update the local state when props change? Here's where we can use various lifecycle methods or React Hooks, depending on whether you're using class-based components or functional components respectively.

Using Lifecycle Methods in Class Components

In class components, we use a lifecycle method called componentDidUpdate(). This method is called immediately after updating occurs. It's like a lookout that keeps an eye on your component and notifies you when something changes.

class MyClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name,
    };
  }

  componentDidUpdate(prevProps) {
    if (prevProps.name !== this.props.name) {
      this.setState({ name: this.props.name });
    }
  }

  render() {
    return <div>{this.state.name}</div>;
  }
}

In the code above, componentDidUpdate() checks if the previous props are different from the current props. If they are, it updates the state.

Using React Hooks in Functional Components

In functional components, we use a Hook called useEffect(). This is a function that accepts two arguments: a function that contains the effect and a dependency array.

function MyFunctionalComponent(props) {
  const [name, setName] = React.useState(props.name);

  React.useEffect(() => {
    setName(props.name);
  }, [props.name]);

  return <div>{name}</div>;
}

In the code above, useEffect() runs after every render. However, by passing [props.name] as the second argument, we're telling it to run the effect only when props.name changes.

Conclusion

Updating the local state when props change in ReactJS may seem like a daunting task at first, but once you understand the reason behind it and how to use lifecycle methods or React Hooks effectively, it becomes a powerful tool in your React toolbox.

Remember, the state is like a memory box, and props are like a baton being passed in a relay race. Detecting changes in props and updating the state accordingly is like setting an alarm that rings when the baton has been passed. Whether you're using class components with their lookout componentDidUpdate(), or functional components with their multifunctional useEffect(), you now have the knowledge to ensure your components react appropriately to changes in props.

Keep honing your ReactJS skills, and soon, you'll be able to create dynamic and responsive web applications that provide an excellent user experience. Happy coding!