Logo
Published on

Passing setState as a prop: You’re doing it wrong

Authors
  • Name
    Twitter

React icon

A key aspect of React development is state management, which allows components to maintain and update their internal data. The setState function plays a pivotal role in this process. However it is essential to understand that passing setState is more likely than not an unnecessary decision and can lead to potential issues in your code in the long run.

It’s Just Unnecessary

React follows a specific lifecycle that governs how components are created, updated, and destroyed. Understanding and adhering to this lifecycle is crucial for efficient state management. The setState function is designed to be used within the component, allowing it to update its state and triggering re-renders at the appropriate stages of the lifecycle. Passing setState as a prop to child components might seem like a convenient solution at first, especially for managing state across different parts of your application, however this approach makes child components overly dependent on the implementation details of their parent.

React’s state management is designed to be predictable and controlled within the component. Tracing and predicting how state changes becomes harder when setState is passed as a prop, leading to potential bugs and maintenance challenges.

Create a handler function instead

// Parent Component  
const Parent = () => {  
  const [state, setState] = useState("");  
    
  return <Child setState={setState} />  
};  
  
// Child Component  
  const Child = ({setState}) => {  
    setData("Data");  
  };  

Notice how setData is passed into Child in order to change the state? This is bad practice. Instead, consider creating a handler function in the parent component that will call setState and pass the handler into the Child.

// Parent component  
const Parent = () => {  
  const [state, setState] = useState("");  
    
  const handlerFunction = (data) => {  
    setState(data)  
}  
    
  return <Child handlerFunction={handlerFunction} />  
};  
  
// Child Component  
  const Child = ({handlerFunction}) => {  
    handlerFunction("Data");  
  };  
  
export default Child

Proper state management is fundamental to building robust React applications. While passing setState as a prop might seem like a shortcut, it introduces unnecessary complexities in the long run. Respecting encapsulation will result in a more predictable and scalable application.