Component API
Components are the building blocks of PyReact applications.
Component Class
- class Component(props)
Base class for all PyReact components.
- Parâmetros:
props (dict) – Properties passed to the component
Example:
from pyreact import element, Component class MyComponent(Component): def __init__(self, props): super().__init__(props) self.state = {'count': 0} def render(self): return element('div', {}, f'Count: {self.state["count"]}')
State Management
- setState(state, callback=None)
Updates the component’s state and triggers a re-render.
- Parâmetros:
state (dict | callable) – New state or function that returns new state
callback (callable, optional) – Function to call after state is updated
Example:
class Counter(Component): def __init__(self, props): super().__init__(props) self.state = {'count': 0} def increment(self): # Update state self.setState({'count': self.state['count'] + 1}) def increment_async(self): # Functional update self.setState(lambda state: {'count': state['count'] + 1}) def increment_with_callback(self): # With callback self.setState( {'count': self.state['count'] + 1}, lambda: print(f'Count is now {self.state["count"]}') )
- state
The component’s state object.
- Type:
Example:
def render(self): return element('div', {}, f'Count: {self.state["count"]}')
Lifecycle Methods
- component_did_mount()
Called immediately after the component is mounted.
Use for: - Fetching data - Setting up subscriptions - Adding event listeners
Example:
class DataFetcher(Component): def component_did_mount(self): self.fetch_data() async def fetch_data(self): # Fetch data from API pass
- component_did_update(prev_props, prev_state)
Called after the component updates.
Example:
class UserViewer(Component): def component_did_update(self, prev_props, prev_state): if prev_props['userId'] != self.props['userId']: self.fetch_user_data()
- component_will_unmount()
Called immediately before the component is unmounted.
Use for: - Cleaning up subscriptions - Canceling timers - Removing event listeners
Example:
class Timer(Component): def component_did_mount(self): self.timer_id = self.start_timer() def component_will_unmount(self): self.stop_timer(self.timer_id)
- should_component_update(next_props, next_state)
Called before rendering. Return False to prevent re-render.
- Parâmetros:
- Retorna:
Whether the component should update
- Tipo de retorno:
Example:
class OptimizedComponent(Component): def should_component_update(self, next_props, next_state): # Only update if data changed return self.props['data'] != next_props['data']
- component_did_catch(error, info)
Called when an error is thrown during rendering.
Example:
class ErrorBoundary(Component): def __init__(self, props): super().__init__(props) self.state = {'has_error': False} def component_did_catch(self, error, info): self.setState({'has_error': True}) log_error(error, info)
Render Method
- render()
Must be implemented by the component. Returns the element tree.
- Retorna:
The element tree to render
- Tipo de retorno:
Element
Example:
class MyComponent(Component): def render(self): return element('div', {}, element('h1', {}, 'Title'), element('p', {}, 'Content') )
Force Update
- force_update(callback=None)
Forces a re-render of the component.
- Parâmetros:
callback (callable, optional) – Function to call after update
Example:
class MyComponent(Component): def some_method(self): # Force re-render without changing state self.force_update()
Function Components
Function components are simpler:
Best Practices
Keep components small - Each component should do one thing
Lift state up - Share state by lifting to common ancestor
Use should_component_update - Optimize performance
Clean up in will_unmount - Always clean up subscriptions
Next Steps
Hooks API - Hooks API reference
State - Learn about state
Lifecycle Methods - Learn about lifecycle