In React, props are typically used as inputs to components, while state represents the internal state of the component. Sometimes, we need to initialize the component's state based on incoming props or update the state when props change. Before React Hooks, we typically implemented this in class components using the componentDidMount and componentDidUpdate lifecycle methods. However, in functional components using React Hooks, we can achieve similar functionality with useState and useEffect.
Using useState to Initialize State
First, we can use useState to initialize state based on props. For example, consider a component that sets the initial value of a counter based on the initialCount prop:
javascriptimport React, { useState } from 'react'; function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Using useEffect to Handle Prop Changes
If props may change during the component's lifecycle and we need to update the state based on these changes, we can use the useEffect hook. For example, suppose we want to reset the counter when the initialCount prop updates:
javascriptimport React, { useState, useEffect } from 'react'; function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); useEffect(() => { setCount(initialCount); // Update count when initialCount changes }, [initialCount]); // Dependency list ensures the effect runs only when it changes return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Summary
By using useState and useEffect, we can flexibly initialize and update state based on props in functional components. This makes functional components equally powerful as class components in handling internal state and responding to external changes.